将ADO记录集复制到Excel工作表中

我正在尝试打开CSV文件并查询它并将结果返回到“ThisWorkbook”的第二个工作表的A列.

我没有收到任何错误,所以我不明白为什么不将记录集复制到excel中.

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset

Set con = New ADODB.Connection
Set rs = New ADODB.Recordset

Dim currentDataFilePath As String
Dim currentDataFileName As String

 Dim nextRow As Integer

currentDataFilePath = "C:\Users\M\folder\"
currentDataFileName = "csv-file"

con.Open "Provider=Microsoft.JET.OLEDB.4.0;" & _
           "Data Source=" & currentDataFilePath & ";" & _
           "Extended Properties=""text;HDR=NO;FMT=Delimited;IMEX=1"""


'rs.ActiveConnection = con

 rs.Open "SELECT Name FROM [" & currentDataFileName & ".csv] WHERE Datatype ='TYPE3'", 
 con

ThisWorkbook.Worksheets("Sheet2").Range("A:A").CopyFromRecordset rs
 rs.Close
con.Close

Set rs = Nothing
Set con = Nothing


End Sub

最佳答案 您可以参考CopyFromRecordset()方法.

基于上面的代码,在rs.Open命令之后你会添加如下内容:

ActiveWorksheet.Range("A1").CopyFromRecordset rs

在这里查看更多:http://msdn.microsoft.com/en-us/library/office/ff839240%28v=office.15%29.aspx

点赞