Reputation: 2982
I'm trying to grab multiple rows from SQL Server and then manipulate them in VBA. I have the connection to the DB working, and I can pull in all the data I need by using the Range().CopyFromRecordSet() function, however I just want to manipulate the data in VBA and not bring the worksheet into it at all.
With the Recordset object I can access the field name and the first row of data, but I can't access all the rows.
When I use the Recordset.GetRows() function, I can access all the data, but it's not structured in any way nor are the field names attached to the record, so it is very difficult to use.
How can I cycle through the different rows in my results in a structured way?
Here's the code I have:
Sub grabData()
Dim dbConn As ADODB.Connection
Set dbConn = openDBConn()
Dim results As ADODB.Recordset
Set results = dbConn.Execute("SELECT Field1, Field2, Field3 FROM Table WHERE Field1 = 'Foobar' AND Field2 > '42'")
'Cycles through the first row of data'
For Each f In results.Fields
Debug.Print f.Name & " " & f
Next
'Cycles through all data, but no Column names'
For Each f In results.GetRows
Debug.Print f
Next
End Sub
Upvotes: 1
Views: 2923
Reputation: 2925
Do While Not results.EOF
For Each f In results.Fields
Debug.Print f.Name & " " & f.Value
Next
results.MoveNext
Loop
Upvotes: 6