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

时间:2016-12-09 19:24:02

标签: excel vba excel-vba text-files oledb

使用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 Driver连接字符串作为查询表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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

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

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