我使用以下宏从已关闭的工作簿中检索数据。为什么debug.print将数据返回到imediate窗口,但数据不会使用语句ActiveSheet.Cells(1, 1).CopyFromRecordset objrecordset![Name] & " " & objrecordset![Number]
和语句ActiveSheet.Cells(1,1).CopyFromRecordset objrecordset
sub adoExcel()
Set objConnection = CreateObject("ADODB.Connection")
Set objrecordset = CreateObject("ADODB.Recordset")
'*************************************************************************************
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Users\sp\Desktop\test ado excel\test.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
'*************************************************************************************
objrecordset.Open "Select * FROM [Sheet1$]", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
'*************************************************************************************
' Loop through the recordset and send data to the Immediate Window
objrecordset.MoveFirst
Do
Debug.Print objrecordset![Name] & " " & objrecordset![Number]
objrecordset.MoveNext
Loop Until objrecordset.EOF
'**************************************************************************************
ActiveSheet.Cells(1, 1).CopyFromRecordset objrecordset![Name] & " " & objrecordset! [Number]
'**************************************************************************************
答案 0 :(得分:1)
当您尝试CopyFromRecordset
时,您已经处于文件结尾(EOF),因此无法复制数据。在循环之前,先在代码中移动CopyFromRecordset
语句。
此方法的参数是RecordSet对象:
.CopyFromRecordset objrecordset