ADODB Connection String for .csv

旧时模样 提交于 2019-12-01 14:14:12

For a text file, Data Source is the folder, not the file. The file is the table (SELECT * FROM ..). See http://www.connectionstrings.com/textfile

I found the answer to my problem. For text files (as stated by Remou) Data Source is just the folder path, without file name. In addition instead of using:

C:\dir\dir2\

I had to use

C:\\dir\\dir2\\

To get file name from full path:

strFilename = Dir(strFilepath)

To get the path only, without a file name:

strFilepath = Left$(strFilepath, InStrRev(strFilepath, "\"))

To change path format from '\' to '\\' I just used:

strFilepath = Replace(strFilepath, "\", "\\")

The problem is solved, thanks for interest.

Here is an update using Microsoft.ACE.OLEDB.16.0 as provider.

Make sure the reference library "Microsoft ActiveX Data Objects 6.1 Library" is added to VBAproject first.

Sub testrunSQLQueryForCSV()
    Dim arrayTest
    arrayTest = runSQLQueryForCSV("C:\xxx\yyyy\", "SELECT * FROM mycsvfile.csv")

    'NOTE: for CSV the Data Source reference is to the directory and the csv file is similar
    'to one "worksheet" in an excel file and is simply referenced in the SQL statement
End Sub


Public Function runSQLQueryForCSV(fileDirPath As String, SQLStatement As String)

    Dim Conn As New ADODB.Connection
    Dim RecSet As New ADODB.Recordset

    With Conn
       .Provider = "Microsoft.ACE.OLEDB.16.0"  'Can use many providers, but this is the latest and it works with csv files also
       .ConnectionString = "Data Source=" & fileDirPath & ";Extended Properties='text'"
    End With

    Conn.Open

    RecSet.Open SQLStatement, Conn
    runSQLQueryForCSV = RecSet.GetRows()

    Conn.Close
    Set RecSet = Nothing
    Set Conn = Nothing
End Function
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!