Excel VBA中使用ADODB连接的csv文件的不同SQL查询

时间:2019-01-14 08:57:31

标签: excel vba csv select adodb

我正在尝试使用Excel VBA中的SQL Select从CSV文件检索数据。这就是我尝试过的。

Sub GetMyCSVData()
Dim xlcon As ADODB.Connection
Dim xlrs As ADODB.Recordset

Set xlcon = New ADODB.Connection
Set xlrs = New ADODB.Recordset

Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer

currentDataFilePath = "C:\MyFolder"
currentDataFileName = "MyFile"

xlcon.Provider = "Microsoft.Jet.OLEDB.4.0"
xlcon.ConnectionString = "Data Source=" & currentDataFilePath & ";" & 
  "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""

xlcon.Open

MyQuery = "SELECT * FROM [" & currentDataFileName & ".csv]"

xlrs.Open MyQuery, xlcon
xlrs.MoveFirst
nextRow = Worksheets("Sheet1").UsedRange.Rows.Count + 1
Worksheets("Sheet1").Cells(nextRow, 1).CopyFromRecordset xlrs

xlrs.Close
xlcon.Close

Set xlrs = Nothing
Set xlcon = Nothing
End Sub

这很好,但是随后,我尝试更精确地查询:

MyQuery = "SELECT MyField FROM [" & currentDataFileName & ".csv]"
xlrs.Open MyQuery, xlcon

这不起作用(错误-2147217904(80040e10))。然后:

MyQuery = "SELECT * FROM [" & currentDataFileName & ".csv] WHERE MyField=10"
xlrs.Open MyQuery, xlcon

这也不起作用(相同的错误)。

当然,我想同时使用这两种方式(从文件中仅选择某些字段,并对不同的字段使用一些“ where子句”。

任何帮助都会得到体现。

1 个答案:

答案 0 :(得分:1)

我强烈假设您的数据中没有字段MyField-也许只是拼写错误。

将查询改回select *以接收所有数据,并放置一些行以转储字段名称。请注意,记录集的字段集合是基于0的。顺便说一句:使用ADO,您无需发出MoveFirst

xlrs.Open MyQuery, xlcon
Dim i As Integer
nextRow = Worksheets("Sheet1").UsedRange.Rows.Count + 1
' Dump fieldnames
For i = 1 To xlrs.Fields.Count
    Worksheets("Sheet1").Cells(nextRow, i) = xlrs.Fields(i - 1).Name
Next i
nextRow = nextRow + 1
Worksheets("Sheet1").Cells(nextRow, 1).CopyFromRecordset xlrs