1
使用VBA,我试图创建Excel查询表以提供文本文件中的数据子集。我想使用Jet OLEDB连接字符串作为查询表Connection
。为什么这会失败?文本文件源上的Excel查询表失败,并使用Jet OLEDB连接字符串
这是程序。
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记录集,然后使用该记录作为的QueryTable 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文本ODBC驱动程序的连接字符串作为的QueryTable 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
非常感谢这方面的帮助。
是的,这有效。不能相信我没有尝试过。 [文档](https://msdn.microsoft.com/en-us/library/office/ff837764.aspx)确实需要“ODBC”;在ODBC连接字符串的开头,但没有为OLEDB指定它。非常感谢! – JBStovers
@JBStovers - 说实话,它更像是“我不知道这是否会奏效”在黑暗中刺伤。 – Comintern