VBA ADODB- Select query using the excel sheet of the same workbook as Database

后端 未结 1 808
予麋鹿
予麋鹿 2021-01-23 06:53

I am novice in VBA so please don\'t mind if the question is of low level.I am trying to run a SQL query where the data has to be extracted from one of the sheets of the same wor

相关标签:
1条回答
  • 2021-01-23 07:10

    Take a look at the below example showing how to create ADODB connection to this workbook, get ADODB recordset from SQL query, retrieve key - value pairs from relation sheet, create and populate a dictionary, and output the values from the recordset and the corresponding values from the dictionary:

    Option Explicit
    
    Sub Test()
    
        Dim oCn As Object
        Dim oRs As Object
        Dim aKeys
        Dim aItems
        Dim i As Long
        Dim oDict As Object
        Dim dProdNum
    
        ' create ADODB connection to this workbook
        Set oCn = CreateObject("ADODB.Connection")
        oCn.Open _
            "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "DataSource='" & ThisWorkbook.FullName & "';" & _
            "Extended Properties=""Excel 8.0;HDR=Yes;FMT=Delimited;IMEX=1;"";"
        ' get ADODB recordset from SQL query
        Set oRs = oCn.Execute("SELECT DISTINCT ProductNumber FROM [Data$] WHERE ProductSource = 'A1'")
    
        ' retrieve key - value pairs from relation sheet
        With ThisWorkbook.Sheets("Relation")
            aKeys = Split(.Range("B1"), ",")
            aItems = Split(.Range("B2"), ",")
        End With
        ' create and populate a dictionary
        Set oDict = CreateObject("Scripting.Dictionary")
        For i = 0 To UBound(aKeys)
            oDict(Trim(aKeys(i)) + 0) = Trim(aItems(i))
        Next
    
        ' output the values from the recordset and the corresponding values from the dictionary
        oRs.MoveFirst
        Do Until oRs.EOF
            dProdNum = oRs.Fields(0).Value
            Debug.Print dProdNum & " - " & oDict(dProdNum)
            oRs.MoveNext
        Loop
    
    End Sub
    

    The output for me is as follows:

    4 - Britanica
    5 - Nestle
    9 - Amul

    Note, connection string in the above code shown for .xls file. In case .xlsm you should use:

        oCn.Open _
            "Provider=Microsoft.ACE.OLEDB.12.0;" & _
            "Data Source='" & ThisWorkbook.FullName & "';" & _
            "Extended Properties=""Excel 12.0 Macro;HDR=Yes;FMT=Delimited;IMEX=1;"";"
    
    0 讨论(0)
提交回复
热议问题