2012-03-16 46 views
1

我試圖從SQL Server中抓取多行,然後在VBA中操縱它們。我有與數據庫連接的工作,並且我可以使用Range()。CopyFromRecordSet()函數獲取所需的所有數據,但是我只想操作VBA中的數據,而不是將工作表放入它中。
使用Recordset對象,我可以訪問字段名稱和第一行數據,但我無法訪問所有行。
當我使用Recordset.GetRows()函數時,我可以訪問所有數據,但它沒有以任何方式構造,也沒有附加到記錄的字段名稱,因此使用起來非常困難。Excel 2010中的SQL Server VBA - 多行數據

如何循環訪問結果中的不同行?

這裏是我的代碼:

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 

回答

6
Do While Not results.EOF 
    For Each f In results.Fields 
     Debug.Print f.Name & " " & f.Value 
    Next 
    results.MoveNext 
Loop 
+0

好極了,我知道我必須失去了一些東西。謝謝! – 2012-03-16 16:13:53

+0

任何時間!樂意效勞。 – transistor1 2012-03-16 16:15:20

+0

+1 Nice One。 :) – 2012-03-16 16:19:16