您确实可以直接在 SQL 语句中使用 DAO 和 ADO 查询其他工作簿,同样通过简单地引用它们的路径来查询 Access 数据库表。相反,在 Access 查询中,您可以查询 Excel 工作簿!这证明了 Jet/ACE SQL 引擎(Windows .dll 文件)不限于任何一种 MS Office 产品或 Windows 程序,而是适用于所有人的工具。
在下面的两个示例中,宏直接连接到第一个工作簿,而在 SQL 查询中,每个宏都间接连接到第二个工作簿。您可以在任一工作簿内部或外部运行代码。两者都INNER JOIN
在FileOne和FileTwo工作表上运行 genric,但任何兼容的 Jet/ACE SQL 语句都应该工作。并且两个输出查询都会导致一个预先存在的RESULTS选项卡。
道
Dim dbE As Object, db As Object, rst As Object
Dim sqlString As String
Dim i As Integer
Const dbOpenDynaset = 2, dbReadOnly = 4
' OPEN DB CONNECTION
Set dbE = CreateObject("DAO.DBEngine.120") 'ALSO TRY: DAO.DBEngine.35 OR .36
Set db = dbE.OpenDatabase("C:\Path\To\FileOne.xlsm", False, True, "Excel 12.0 Xml;HDR=Yes")
' OPEN QUERY RECORDSET
sqlString = " SELECT * FROM [TAB$] t1" _
& " INNER JOIN (SELECT * FROM" _
& " [Excel 12.0 Xml;HDR=Yes;Database=C:\Path\To\FileTwo.xlsm].[TAB$]) t2" _
& " ON t1.ID = t2.ID"
Set rst = db.OpenRecordset(sqlString, dbOpenDynaset, dbReadOnly)
' COLUMNS
For i = 1 To rst.Fields.Count
Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name
Next i
' DATA ROWS
Worksheets("RESULTS").Range("A2").CopyFromRecordset rst
rst.Close
db.Close
Set rst = Nothing
Set db = Nothing
Set dbE = Nothing
ADO
Dim conn As Object, rst As Object, fld As Object
Dim strConnection As String, strSQL As String
Dim i As Integer
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' OPEN DB CONNECTION
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\FileOne.xlsm';" _
& "Extended Properties=""Excel 12.0 Xml;HDR=YES;"";"
conn.Open strConnection
' OPEN QUERY RECORDSET
strSQL = " SELECT * FROM [TAB$] t1" _
& " INNER JOIN (SELECT * FROM" _
& " [Excel 12.0 Xml;HDR=Yes;Database=C:\Path\To\FileTwo.xlsm].[TAB$]) t2" _
& " ON t1.ID = t2.ID"
rst.Open strSQL, conn
' COLUMNS
For i = 1 To rst.Fields.Count
Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name
Next i
' DATA ROWS
Worksheets("RESULTS").Range("A2").CopyFromRecordset rst
rst.Close
conn.Close
Set rst = Nothing
Set conn = Nothing