VBA 循环并写入 ADODB 记录集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6794135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA looping through and writing ADODB Recordset
提问by jz3
I'm new to working with recordsets, and I'm working on something where I retrieve a recordset from a sql server and then I need to loop through it pasting the values in an excel spreadsheet.
我是记录集的新手,我正在做一些事情,我从 sql server 检索记录集,然后我需要遍历它,将值粘贴到 excel 电子表格中。
The order of the fields in the recordset is already correct, so I should be able to just move from cell to cell pasting each value within a range, but I'm not sure exactly how to do it. I know the recordset is correct because I outputed it to a file and everything looked in order.
记录集中字段的顺序已经正确,所以我应该能够从一个单元格移动到另一个单元格,粘贴一个范围内的每个值,但我不确定如何去做。我知道记录集是正确的,因为我将它输出到一个文件中,并且一切看起来都井井有条。
This is my code so far:
到目前为止,这是我的代码:
Public Sub retrieve()
Dim rsTest As ADODB.Recordset
Set rsTest = New ADODB.Recordset
Set rsTest = DataManager.GetData()
Sheets("Planners").Activate
Dim cel As Range
Dim i As Integer
Dim rsFields As Variant
Do While Not rsTest.EOF
For Each cel In ActiveSheet.Range("A3:H1000").Cells
For Each rsFields In rsTest.Fields
cel = rsTest(rsFields.Name)
Next
Next
Loop
End Sub
Thanks in advance for any and all help.
在此先感谢您的任何帮助。
回答by Tim Williams
If you want all the recordset fields then you can just do this:
如果你想要所有的记录集字段,那么你可以这样做:
Public Sub retrieve()
Dim rsTest As ADODB.Recordset
Set rsTest = DataManager.GetData()
If Not rsTest.EOF Then
Sheets("Planners").Range("A3").CopyFromRecordset rsTest
End If
End Sub