【发布时间】:2016-01-14 11:59:02
【问题描述】:
我从 VBA 中查询了一个 MS-Access 数据库,并将结果集返回到一个数组中,如下所示:
Sub ChartData()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
' Hard code database location and name
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\server1\myDB.mdb"
' Construct SQL query
strSql = "TRANSFORM Count(Names) AS CountOfNames SELECT Ticker FROM Pricing GROUP BY Ticker PIVOT Source; "
' execute the query, and return the results to the rs object
cn.Open strConnection
Set rs = cn.Execute(strSql)
' Copy the result set to an array
Dim myArr() As Variant
myArr = rs.GetRows
' Close the connection
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
...
End Sub
接下来,我想在 myArr 中插入一列,它具有动态维度。我试图为此使用ReDim Preserve,但了解到ReDim Preserve 只允许更改第一个维度。例如,以下代码导致运行时错误,下标超出范围:
Sub ChartData()
...
Dim newRowCount As Integer
Dim newColCount As Integer
newRowCount = UBound(myArr, 2) + 1
newColCount = UBound(myArr, 1) + 2
ReDim Preserve myArr(newColCount, newRowCount) ' Run-time error here
End Sub
有没有一种优雅的方法来解决这个ReDim Preserve 限制以插入列而不擦除数据?
谢谢!
【问题讨论】:
-
在前面添加额外的列
strSql = " SELECT p.*, null as AddedColumn FROM Pricing p " -
其实我的SQL查询是一个Crosstab Query。问题已更新。但是,我当然愿意通过简单地更改 SQL 语句来获得解决方案。
-
如果你不能通过 SQL 做到这一点,那么创建一个函数来创建一个具有所需维度的新数组并复制数据。
-
我不确定。我可以通过 SQL 查询吗?
-
我不知道 - 我不能在这里测试...