我在两个不同的工作簿中分别有一个工作表。两张纸都相同,只是纸张2有3-4张记录。我使用左连接来获取这些记录但得到语法错误。任何帮助表示赞赏。谢谢。 例如: -
Workbook1 Workbook2
Sheet 1 Sheet 1
ID Name ID Name
123 Jim 123 Jim
255 jack 255 jack
275 alice 275 alice
300 Bob
所以当你看到第一个有4个记录而第二个有3个时,情况总是如此。我只需要在第一张和记录中找到额外的记录。
Sub get_unknowns()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Set x = Workbooks.Open("A.xlsx")
Set y = Workbooks.Open("B.xlsx")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [x.Worksheets("Sheet1")] LEFT JOIN [y.Worksheets("Sheet1")] ON [x.Worksheets("Sheet1")$].[PrimaryID] NOT IN " & _
"[[y.Worksheets("Sheet1")$].[primaryId]", cn
With Worksheets("Sheet3")
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
根据建议我做了一些更改并尝试过,我在同一个工作簿中有两张图并尝试使用左连接
Sub get_employees()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
cn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.Path & "H:\testing\demo\test1.xlsx;" & _
"Extended Properties=""Excel 12.0"";"
rs.Open "SELECT * FROM [Sheet1$] as A LEFT JOIN [Sheet2$] as B ON A.[Id] =B.[Id]", cn
With Worksheets("Sheet3")
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
现在它抛出运行时错误3709,该连接不能用于执行此操作。在这种情况下它是关闭的还是无效的。
答案 0 :(得分:3)
嗯,有几个问题:
a)您无法使用JET打开xlsx文件,需要ACE,如:
cn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.Path & "\Workbookname.xlsx;" & _
"Extended Properties=""Excel 12.0"";"
b)您不需要在VBA中打开工作簿;连接本身就是这样,但是:
c)连接只计算一个工作簿。我不认为跨工作簿查询是可能的
d)FROM
部分中的表的语法是[Sheetname$]
,您必须将其正确填充到字符串中(VBA变量的名称不会在查询字符串中帮助)。此工作表必须位于通过连接字符串打开的工作簿中。
答案 1 :(得分:0)
您的连接字符串似乎不正确,而您尚未打开连接。试试这样的事情
Sub get_employees()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=Yes"";"
.Open
End With
rs.Open "SELECT * FROM [Sheet1$] as A LEFT JOIN [Sheet2$] as B ON A.[Id] =B.[Id]", cn, adOpenKeyset, adLockReadOnly
With Worksheets("Sheet3")
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub