我对将SQL与VBA结合使用非常陌生。
我处于一种情况,我有两个工作簿,并且使用SQL将它们与一个公用列结合在一起。我使用此website将两个工作簿都作为数据库。
我从互联网使用的示例让我从一个excel文件中获取数据,因此他只是打开了与一个数据库的连接,但是当我希望两个excel文件充当数据库时我应该怎么做。想要做到这一点,这样我就可以结合两者运行SQL查询
Sub ReadDB()
Dim mainWorkBook As Workbook
Dim intRowCounter
Set mainWorkBook = ActiveWorkbook
intRowCounter = 2
mainWorkBook.Sheets("Sheet2").Range("A2:Z100").Clear
Set Connection = CreateObject("ADODB.Connection")
Connection.Open "DSN=BDRReport"
Connection.Open "DSN=SumitODBC" 'this is where i am running into the problem i think
strQuery = "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;"
Set resultSet = Connection.Execute(strQuery)
Do While Not resultSet.EOF
mainWorkBook.Sheets("Sheet2").Range("A" & intRowCounter).Value = resultSet.Fields("Master Book Name").Value
mainWorkBook.Sheets("Sheet2").Range("B" & intRowCounter).Value = resultSet.Fields("App Book Name").Value
intRowCounter = intRowCounter + 1
resultSet.movenext
Loop
resultSet.Close
End Sub