Excel 文本文件源上的 QueryTable 使用 Jet OLEDB 连接字符串失败

Excel QueryTable on Text File source fails with Jet OLEDB Connect String

使用 VBA,我正在尝试创建一个 Excel 查询表以提供来自文本文件的数据子集。我想使用 Jet OLEDB 连接字符串作为查询表 Connection。为什么会失败?

这是程序。

Sub OledbTest1()  'FAILS.
'Create querytable with oledb connect string.
    Const strConn = _
        "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Users\RSJCB\Desktop\;" & _
        "Extended Properties=""text;HDR=Yes;FMT=Delimited"""
    Dim wsht As Worksheet
    Set wsht = ThisWorkbook.Worksheets.Add()
    With wsht
        'The next line errors with 1004: Application-defined of object-defined error
        .QueryTables.Add strConn, .Range("A1"), "SELECT TOP 10 * FROM [TestFile.csv]"
        .QueryTables(1).Refresh
    End With
    Set wsht = Nothing
End Sub

如果我用它来创建 ADO 记录集,然后将该记录集用作查询表,连接字符串就可以工作 Connection

Sub OledbTest2()  'SUCCEEDS.
'Create querytable with ado recordset opened using oledb connect string.
    Const strConn = _
        "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Users\RSJCB\Desktop\;" & _
        "Extended Properties=""text;HDR=Yes;FMT=Delimited"""
    Const strSql = "SELECT TOP 10 * FROM [TestFile.csv]"
    Dim wsht As Worksheet
    Dim rst As New ADODB.Recordset
    rst.Open strSql, strConn
    Set wsht = ThisWorkbook.Worksheets.Add()
    With wsht
        'The next line errors with 1004: Application-defined of object-defined error
        .QueryTables.Add rst, .Range("A1")
        .QueryTables(1).Refresh
    End With
    Set wsht = Nothing
    Set rst = Nothing
End Sub

如果我使用 Microsoft Text ODBC 驱动程序连接字符串作为查询表,它也可以工作 Connection。但是,这似乎工作得有点慢,我在实际代码中读取了 700K 条记录。此外,我从未能够与查询表建立 OLEDB 连接,我想知道如何做。

Sub OdbcTestQtbl()  'SUCCEEDS.
'Create querytable with odbc connect string.
    Const strConn = _
        "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
        "Dbq=C:\Users\RSJCB\Desktop\;" & _
        "Extensions=asc,csv,tab,txt;"
    Dim wsht As Worksheet
    Set wsht = ThisWorkbook.Worksheets.Add()
    With wsht
        .QueryTables.Add "ODBC;" & strConn, .Range("A1"), "SELECT TOP 10 * FROM [TestFile.csv]"
        .QueryTables(1).Refresh
    End With
    Set wsht = Nothing
End Sub

非常感谢对此的任何帮助。

你需要让Excel知道驱动是OLEDB驱动。只需将(显然未记录的)提供程序说明符附加到连接字符串的开头:

.QueryTables.Add "OLEDB;" & strConn, .Range("A1"), "SELECT TOP 10 * FROM [TestFile.csv]"