如何在VBA中使用SQL将两个工作簿与一个公共列合并

时间:2018-10-24 19:03:52

标签: sql excel vba excel-vba adodb

我相信我也可以通过Macro来做到这一点,但是我想在VBA中被介绍给ADODB和SQL查询。数据集不在Access中,而是在单独的工作簿中,这两个工作簿的SQL查询如下:

SELECT getRollpHierRpt.Field1, ['App].[Master Book Name], ['App].[App Book Name], ['App].[Secondary App Book Name], ['App].[App Code], ['App].[App Book Status], ['App].[Book Transit], ['App].[Transit Desc], ['App].[Legal Entity Id], ['App].[Legal Entity Desc]
FROM ['App] INNER JOIN getRollpHierRpt ON ['App].[Book Transit] = getRollpHierRpt.Field1;

我在互联网上看到的示例包括与Access / SQL Server的连接,但是如果数据集是两个excel工作簿?

Sub MergeIt()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
 With conn1
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data 
Source=C:\Users\amzubaid\Desktop\Practice Merging\13-10-2017.xlsm;" & 
"Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
.Open
  End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data 
Source=C:\Users\amzubaid\Desktop\Practice Merging\20181015-Practice.xlsm;" & "Extended Properties=""Excel 12.0 Macro;HDR=YES';IMEX=1"""
  .Open
 End With
Dim rsSmall As New Recordset
rsSmall.Open "select [Field1] from [getRollpHierRpt$]", conn1
 Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell

rsBig.Open "select [App Code],[Legal Entity Desc]," & rsSmall("Field1") & " 
 As GetRollPH from [getRollpHierRpt$] where [BookTransit] = " & 
 rsSmall("Field1"), conn2
 r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF  'end if file
rsSmall.Close
conn1.Close
conn2.Close

End Sub

1 个答案:

答案 0 :(得分:0)

您将需要设置每个工作簿的连接。实际上,这取决于将每个工作簿视为数据库中的表。每个工作簿中必须具有列标题,这些列标题被视为字段名称。尝试this了解详情

好,所以这似乎不太可能-因此,一种可能的解决方法是打开较小的表,然后逐步处理它,并使用各个值从较大的表中检索所需的记录:这是一个使用两个名为Testfile1的工作簿的示例和testfile2。每个文件都包含一个名为“ test”的工作表以及一些数据,这些数据在testfile2中的列标题为“ TestC”和“ TestD”,而第一个(链接)文件在testfile1中称为“ TestA”。 (这需要在VBE,工具,参考中引用“ Microsoft Active X数据对象”库)

Sub TwoFiles()
Dim conn1 As New ADODB.Connection
Dim conn2 As New ADODB.Connection
With conn1
    .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile1.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
    .Open
End With
With conn2
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\testfile2.xlsm;" & "Extended Properties='Excel 12.0 Macro;HDR=YES';"
.Open
End With
Dim rsSmall As New Recordset
rsSmall.Open "select [testA] from [test$]", conn1
Dim r As Range
Dim rsBig As New Recordset
Do
Set r = Range("a" & Rows.Count).End(xlUp).Offset(1, 0) 'first unoccupied cell

rsBig.Open "select [TestC],[TestD]," & rsSmall("testA") & " As GetRollPH from [test$] where [testC] = " & rsSmall("testA"), conn2
r.CopyFromRecordset rsBig
rsBig.Close
rsSmall.MoveNext
Loop Until rsSmall.EOF  'end if file
rsSmall.Close
conn1.Close
conn2.Close


End Sub