问题
i'm having difficult to create on query with two different database in ADO, i need to make a lot of queries with different sources, for example select from excel file with left join in access file.
When i use two different excel files like the code below works fine.
Dim SQL As String
Dim CN As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set CN = New ADODB.Connection
Set rs = New ADODB.Recordset
'Open connection
CN.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ExcelTable.xlsx" & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
SQL = " SELECT * FROM [table1$] t1" _
& " LEFT JOIN (SELECT * FROM" _
& " [Excel 12.0 Xml;HDR=Yes;Database=C:\db1.xlsx].table2) t2" _
& " ON t1.[reftable1] = t2.reftable2"
rs.Open SQL, CN, adOpenDynamic
If rs.EOF = False Then
Do While Not rs.EOF
debug.print rs("field1")
rs.MoveNext
Loop
End If
rs.Close
CN.Close
But i need to make this query with left join in the access file and i got the error: "cannot update database or object is read only" when i try to open the record set.
My code:
Dim SQL As String
Dim CN As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set CN = New ADODB.Connection
Set rs = New ADODB.Recordset
'Open connection
CN.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ExcelTable.xlsx" & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
SQL = " SELECT * FROM [table1$] t1" _
& " LEFT JOIN (SELECT * FROM" _
& " [Data Source=C:\db1.accdb].table2) t2" _
& " ON t1.[reftable1] = t2.reftable2"
rs.Open SQL, CN, adOpenDynamic
If rs.EOF = False Then
Do While Not rs.EOF
debug.print rs("field1")
rs.MoveNext
Loop
End If
rs.Close
CN.Close
回答1:
Remove the Excel 12.0 spec from main connection string since that gets applied to both sources. Instead open the access database first without Excel 12.0 spec
CN.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=c:\db1.accdb"
now specify the extended property of Excel 12.0 only for the workbook
SQL = " SELECT t1.name, t2.unit FROM [Excel 12.0;HDR=Yes;Database=C:\ExcelTable.xlsx;].[Table1$] t1" _
& " LEFT JOIN (SELECT * FROM Table1) t2" _
& " ON t1.reftable1 = t2.reftable2"
Hope this helps.
来源:https://stackoverflow.com/questions/55554597/how-to-select-from-excel-table-with-left-join-in-access-database-excel-vba