How to select from excel table with left join in access database - EXCEL VBA

一曲冷凌霜 提交于 2021-02-07 22:43:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!