Run access query from Excel and pass parameters to the query

后端 未结 2 1692
情书的邮戳
情书的邮戳 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 <full path to Access DB>
    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.

    0 讨论(0)
  • 2021-01-27 23:17

    Here is one possibility:

    Dim cn As Object
    Dim strFile As String
    Dim strCon As String
    Dim strSQL As String
    
    strFile = "C:\docs\Test.mdb"
    
    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile
    
    ''Late binding, so no reference is needed
    Set cn = CreateObject("ADODB.Connection")
    
    cn.Open strCon
    
    strSQL = "INSERT INTO ATable (AField) " _
    & "VALUES (" & Sheet1.[A1] & ")"
    
    cn.Execute strSQL
    
    cn.Close
    Set cn = Nothing
    

    You can also refer in-line in the sql to a dataset from Excel.

    EDIT re comments

    Using a command:

    strSQL = "SELECT * FROM ATable " _
    & "WHERE AField = @AField"
    
    With cmd
        Set .ActiveConnection = cn
        .CommandText = strSQL
        .CommandType = 1 'adCmdText
    
        ''ADO Datatypes are often very particular
        ''adSmallInt = 2 ; adParamInput = 1
        .Parameters.Append .CreateParameter("@AField", 2, 1, , Sheet1.[A1])
    
    End With
    Set rs = cmd.Execute 
    

    See also: http://support.microsoft.com/kb/181782

    0 讨论(0)
提交回复
热议问题