与.csv文件的Recordset连接错误

时间:2015-11-16 19:05:02

标签: excel vba csv adodb

我正在尝试加入两个CSV文件。 目前我正在尝试添加以下代码。我添加了一个验证,如果连接打开了“If Not objConnection Is Nothing Then”但是假设连接是打开的。当我运行代码时,我收到以下错误消息:

error msg

大致翻译为: 执行时间发生错误'2147217904(80040e10)':
尚未指定某些必需值。

我已加载以下库:

references

代码如下:

Dim objConnection As ADODB.Connection
Dim objrecordset As ADODB.Recordset


fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV File (*.csv),(*.csv)", Title:="Select first CSV file")
If fNameAndPath = False Then
    Exit Sub
End If

fNameAndPath2 = Application.GetOpenFilename(FileFilter:="CSV File (*.csv),(*.csv)", Title:="Select second CSV file")
If fNameAndPath2 = False Then
    Exit Sub
End If

Set objConnection = CreateObject("ADODB.Connection")
Set objrecordset = CreateObject("ADODB.Recordset")

strPath = Left(fNameAndPath, InStrRev(fNameAndPath, "\") - 1)
Filename = Mid(fNameAndPath, InStrRev(fNameAndPath, "\") + 1)

strPath2 = Left(fNameAndPath2, InStrRev(fNameAndPath2, "\") - 1)
Filename2 = Mid(fNameAndPath2, InStrRev(fNameAndPath2, "\") + 1)

    With objConnection
        .Provider = "Microsoft.Jet.OLEDB.4.0"
        .ConnectionString = "Data Source=" & strPath & _
        ";Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
        .Open
    End With

    strSql = "SELECT * FROM " & Filename & " as file1, " _
            & "" & Filename2 & " as file2" _
            & " WHERE file1.[APOYO] = file2.[APOYO]"


If Not objConnection Is Nothing Then
    If (objConnection.State And adStateOpen) = adStateOpen Then
        Set objrecordset = objConnection.Execute(strSql)


    End If
End If

1 个答案:

答案 0 :(得分:0)

从头开始重启。

此代码有效:

Sub leerCSV()


On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
      "Data Source=" & strPathtoTextFile & ";" & _
      "Extended Properties=""text;HDR=YES;FMT=Delimited"""

strSql = "SELECT * FROM file.csv F1 " _
& " LEFT JOIN file2.csv F2 ON F1.[c1] = F2.[c1] "


objRecordset.Open strSql, objConnection, adOpenStatic, adLockOptimistic,     adCmdText
MsgBox "Registros: " & objRecordset.RecordCount

Debug.Print Now


Do Until objRecordset.EOF
    Debug.Print "Name: " & objRecordset.Fields.Item("APOYO") & " Department: " & objRecordset.Fields.Item("O&D") & " Extension: " & objRecordset.Fields.Item("FECHA")
    objRecordset.MoveNext
Loop

''Tidy up
objRecordset.Close
objConnection.Close

End Sub