I've queried an MS-Access database from within VBA, and returned the result set to an array, as follows:
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
Next, I'd like to insert one column into myArr, which has dynamic dimensions. I've attempted to use ReDim Preserve for this purpose, but learned that ReDim Preserve will only allow changing the first dimension. For example, the following code results in the Run-time error, Subscript out of range:
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
Is there an elegant way to work-around this ReDim Preserve limitation to insert a column without wiping the data?
Thanks!
strSql = " SELECT p.*, null as AddedColumn FROM Pricing p "