Run access query from Excel and pass parameters to the query

后端 未结 2 1693
情书的邮戳
情书的邮戳 2021-01-27 22:44

How to execute a query in MS Access db from Excel VBA code or macro. MS-Access query accepts some parameters, that needs to be passed from Excel. Thanks

2条回答
  •  醉梦人生
    2021-01-27 23:14

    This uses ADODB.

    Set m_Connection = New Connection
    
    If Application.Version = "12.0" Then
        m_Connection.Provider = "Microsoft.ACE.OLEDB.12.0"
    Else
        m_Connection.Provider = "Microsoft.Jet.OLEDB.4.0"
    End If
    
    m_Connection.Open 
    If m_Connection.State > 0 Then
    
        Dim rsSource As New Recordset
        rsSource.Open strQuery, m_Connection, adOpenForwardOnly, adLockReadOnly
    
        Dim result As Long
        Dim rngTarget As Range
        rngTarget = ThisWorkbook.Worksheets(m_SheetName).Range("A1")
    
        If Not rsSource.BOF Then
            result = rngTarget.CopyFromRecordset(rsSource)
        End If
    
        If rsSource.State Then rsSource.Close
        Set rsSource = Nothing
    
    End If
    

    So it runs the query and puts it where you like. strQuery is the name of a query in the db or an SQL string.

提交回复
热议问题