我尝试合并来自多个工作簿的数据,并在当前工作簿中使用它而不是VLOOKUP函数。因此,我不希望返回键列,而只返回那些与当前工作簿的键列中的条件匹配的键。
我收到“ FROM子句中的语法错误。”
没有“ RIGHT JOIN”部分,一切正常。我使用ADO。
"SELECT t1.number " & _
"FROM" & _
"(SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsm' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']" & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']) t1" & _
"RIGHT JOIN [Sheet1$] " & _
"IN '" & ThisWorkbook.FullName & "' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] t2 ON t2.key = t1.key;"
数据看起来像
ThisWorkbook.Fullname:
key | someColumns | number
k1 | somedata |
k3 | somedata |
k5 | somedata |
\ Src1.xlsm(也是Src2):
key | number
k1 | 15
k2 | 11
k3 | 8
k4 | 16
k5 | 7
很可能导致Thisworkbook.fullname
key | someColumns | number
k1 | somedata | 15
k3 | somedata | 8
k5 | somedata | 7
答案 0 :(得分:0)
尝试
Dim Ws As Worksheet
Dim Rs As Object
Sub getRs(strSQL As String)
Dim strConn As String
Dim i As Integer
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0;"
Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn
End Sub
Sub test()
Dim strQuery As String
strQuery = "SELECT t1.number " & _
"FROM [Sheet1$] as t2 LEFT JOIN " & _
"(SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsm' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']) as t1 " & _
"ON t1.key = t2.key Where not isnull(t2.key) "
getRs strQuery
Range("c2").CopyFromRecordset Rs
Rs.Close
Set Rs = Nothing
End Sub