使用VBA-Excel跨多个数据库进行SQL查询

时间:2016-07-24 18:06:44

标签: sql excel vba dao data-access-object

使用Excel 2010,SQL和DAO

我正在尝试对位于当前电子表格之外的表执行查询。在Access中,这对于链接表/数据库来说是微不足道的,但是在excel中使用VBA,我受到了阻碍。

假设这些:

String A = "00007c3fff1f3b06738f390079c627c3ffe3fb11f0007c00fff07ff03f003000" //Image 1
String B = "6000fc3efb1f1b06638f1b0071c667c7fff3e738d0007c00fff03ff03f803000" //Image 2

我想在第三个excel文件中执行一个查询,就像这样[使用点符号进行解释,而不是编码....] - 一个简单的例子:

ExcelFileOne; Tab; various headed field/columns
ExcelFileTwo; Tab; various headed field/columns

基本上,我想复制Access本身会为该链接文件复制的内容。

指向正确的方向?

[[我可以使用指针指向为什么在连接中使用“Excel 8.0 ...”工作或在Excel2010上失败,包含宏文件,以及如何在对用户关闭的网络/系统中加载12或14变体....]]

1 个答案:

答案 0 :(得分:3)

您确实可以直接在SQL语句中使用DAO和ADO查询其他工作簿,同样通过简单地引用其路径来查询Access数据库表。相反,在Access查询中,您可以查询Excel工作簿!这证明了Jet / ACE SQL引擎(Windows .dll文件)不仅限于任何一个MS Office产品或Windows程序,而是一个适用于所有人的工具。

在下面的两个示例中,宏直接连接到第一个工作簿,在SQL查询中,每个间接连接到第二个工作簿。您可以在工作簿内部或外部运行代码。两者都在 FileOne FileTwo 工作表上运行genric INNER JOIN,但任何兼容的Jet / ACE SQL语句都应该有效。并且两者都在预先存在的结果选项卡中输出查询结果。

<强> DAO

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