简体   繁体   English

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

[英]Different SQL queries in Excel VBA for csv files using ADODB connection

I am trying to retrieve data from CSV file using a SQL Select in Excel VBA. 我正在尝试使用Excel VBA中的SQL Select从CSV文件检索数据。 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)). 这不起作用(错误-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. 当然,我想将两者结合使用(从文件中仅选择某些字段,并对不同的字段使用一些“ where子句”。

Any help would be appretiated. 任何帮助将不胜感激。

I strongly assume that you don't have a field MyField in your data - maybe it's just a misspelling. 我强烈认为您的数据中没有字段MyField也许只是拼写错误。

Change the query back to select * to receive all data and put some lines to dump the fieldnames. 将查询改回以select *以接收所有数据,并添加一些行以转储字段名称。 Note that the field-collection of a Recordset is 0-based. 请注意,记录集的字段集合是基于0的。 Btw: with ADO , you don't need to issue a MoveFirst : 顺便说一句:使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM