I am trying to retrieve data from CSV file using a SQL Select in Excel VBA. This is what I've tried.
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
This is working fine, but then, I tried to be more precise with my query:
MyQuery = "SELECT MyField FROM [" & currentDataFileName & ".csv]"
xlrs.Open MyQuery, xlcon
This is not working (Error -2147217904 (80040e10)). And then:
MyQuery = "SELECT * FROM [" & currentDataFileName & ".csv] WHERE MyField=10"
xlrs.Open MyQuery, xlcon
This is also not working (same error).
Of course, I would like to use a combination of both things (select only some fields from the file and use some "where clauses" for different fields.
Any help would be appretiated.