我想在Excel VBA中使用ADODB处理.csv文件。我尝试在网上找到一些字符串,但它们似乎都没有用。我正在使用文件路径:
strVFile = Application.GetOpenFilename("CSV (*.csv), *.csv")
然后我将strVFile
作为参数传递给子objReport.Load strVFile
。子标题是:Public Sub Load(ByVal strFilename As String)
。
然后我尝试使用string:
建立ADODB连接pconConnection.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilename & _
";Extended Properties=""text;HDR=Yes;FMT=Delimited(;)"";Persist Security Info=False"
pconConnection.Open
当我运行宏并选择CSV文件时,出现“给定路径不是有效路径”的错误。我做错了什么?
编辑(代码),
模块mdlReport
Public Sub Report()
Dim objReport As clsReport
MsgBox "Please select .csv file", vbInformation + vbOKOnly
strVFile = Application.GetOpenFilename("CSV (*.csv), *.csv")
If strVFile <> False Then
Set objReport = New clsReport
objReport.Load strVFile
End If
End Sub
Class clsReport
Private pconConnection As ADODB.Connection
Private prstRecordset As ADODB.Recordset
Private Sub Class_Initialize()
Set pconConnection = New ADODB.Connection
pconConnection.ConnectionTimeout = 40
End Sub
Public Sub Load(ByVal strFilename As String)
pconConnection.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilename & _
";Extended Properties=""text;HDR=Yes;FMT=Delimited(;)"";Persist Security Info=False"
pconConnection.Open
End Sub
答案 0 :(得分:8)
对于文本文件,Data Source
是文件夹,而不是文件。该文件是表(SELECT * FROM ..)。见http://www.connectionstrings.com/textfile
答案 1 :(得分:1)
我找到了问题的答案。对于文本文件(如Remou所述)Data Source
只是文件夹路径,没有文件名。另外,而不是使用:
C:\dir\dir2\
我必须使用
C:\\dir\\dir2\\
从完整路径获取文件名:
strFilename = Dir(strFilepath)
仅获取路径,没有文件名:
strFilepath = Left$(strFilepath, InStrRev(strFilepath, "\"))
要将路径格式从'\'更改为'\\',我刚刚使用:
strFilepath = Replace(strFilepath, "\", "\\")
问题已经解决,感谢您的兴趣。
答案 2 :(得分:0)
这是使用Microsoft.ACE.OLEDB.16.0作为提供程序的更新。
确保首先将参考库“ Microsoft ActiveX数据对象6.1库”添加到VBAproject。
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