excel vba运行sql命令从CSV文件中获取所选数据

时间:2018-04-25 11:37:59

标签: sql excel-vba vba excel

我正在尝试根据下拉列表中选定的组织名称运行sql命令,然后从具有相同组织名称的csv文件中导入所有匹配的行,我可以使用ODBC连接,但是当它改为CSV连接时它不起作用,任何帮助都将非常感激

Public Const ConnStringCSV = "Microsoft.Jet.OLEDB.4.0" & _
"Data Source=T:\DataFeed;" & _
"Extended Properties=""text;HDR=yes;FMT=Delimited(,)"";Persist Security Info=False"
im conn As New ADODB.Connection
Sub import_from_csv()
Dim conn As New ADODB.Connection
Dim connMasterConnection As New ADODB.Connection
Dim rsObj As New ADODB.Recordset
Dim Ws_FData As Worksheet
Dim Ws_UserForm As Worksheet
Dim strSQL As String
Dim org as String
Dim iCols As Integer
Dim varname1 As String
Dim ops As String

Set Ws_Fdata = ActiveWorkbook.Worksheets("FData")

    'Delete the last results before we start the new run
Ws_FData.Cells.Clear

    'The value of the organisation that the users chooses
org = Sheet5.Range("A1").Value

connMasterConnection.Open ConnStringCSV

    'varname1 is the SQL Code I need to look for a match in org name from a 
    'search 'list I have , then add all the rows of data
     'The CSV File is called OrgCheck.csv 

rsObj.Open varname1, connMasterConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
For iCols = 0 To rsObj.Fields.Count - 1
Ws_FData.Cells(1, iCols + 1).Value = rsObj.Fields(iCols).Name
Next 
Ws_FData.Range("A2").CopyFromRecordset rsObj
connMasterConnection.Close`enter code here`

1 个答案:

答案 0 :(得分:0)

缺少分号。它应该是:

Public Const ConnStringCSV = "Microsoft.Jet.OLEDB.4.0;" & _