sqlexcelvbaadodb

Subquery using SELECT ADODB Excel Not Working (VBA)


I'm trying to select data from other table using subquery in ADODB Excel. Here is my code:

Sub CopyData()
    Dim cmd As String
    If OpenConnection() = True Then 'The connection function already created in my module
        cmd = "SELECT * FROM (SELECT [SheetName] FROM `Breakdown structure library$` WHERE [Name (Name *)]='WBS');"
        Rcdset.Open cmd, Con, adOpenStatic, adLockBatchOptimistic
        With shTemp
            .Cells.Delete
            .Range("A1").CopyFromRecordset Rcdset
        End With
        If Con.State Then Con.Close
    End If
End Sub

The result is error :

Run-time error '-2147217904' (80040e10): No value given for one or more parameters

I know what's going on. You have to add '$' at the end of the sheet name to execute query in ADODB Excel such as:

SELECT * FROM `MyTable` '(not working in ADODB Excel, but working in Access database)
SELECT * FROM `MyTable$` '(working in ADODB Excel)

I don't know how to make sql subquery to identify the table automaticaly, where we are going to select the data.


Solution

  • You can't use a sub-select to determine the table name of the select, use 2 queries.

        Dim sTableName As String, SQL As String, rcdset As New ADODB.Recordset
        If OpenConnection() = True Then 'The connection function already created in my module
          
            SQL = " SELECT [SheetName] " & _
                  " FROM `Breakdown structure library$` " & _
                  " WHERE [Name (Name *)]='WBS';"
            sTableName = con.Execute(SQL)(0)
    
            SQL = " SELECT * FROM [" & sTableName & "$]"
            rcdset.Open SQL, con, adOpenStatic, adLockBatchOptimistic
            With shTemp
                .Cells.Delete
                .Range("A1").CopyFromRecordset rcdset
            End With
            If con.State Then con.Close
         
         End If