VBA使用CSV文件中的列索引获取SQL结果

时间:2019-01-04 10:29:59

标签: excel vba excel-vba

使用vba宏,我使用了以下查询,并且可以获得结果

strsQL = "SELECT name,address, balance1,balance2,balance3 FROM userInfo.csv"

如果有可能使用column index而不是在VBA宏中使用列名(地址)来获取sql结果

1 个答案:

答案 0 :(得分:0)

尝试一下。

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:\My Data Folder\"
currentDataFileName = "My Data File"

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

xlcon.Open

xlrs.Open "SELECT FirstName, Surname, Age FROM [" & currentDataFileName & ".csv] WHERE SomeNumber > 10", 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