Calling stored procedure using VBA

前端 未结 2 907
半阙折子戏
半阙折子戏 2020-12-01 13:18

I am working in Access 2010 user front-end with a Microsoft SQL Server 2008 back-end.

The tables in Access are all linked to the SQL server database.

I have

相关标签:
2条回答
  • 2020-12-01 13:41

    Victoria,

    You can run a stored procedure using ADO, like below...

    Set mobjConn = New ADODB.Connection
    mobjConn.Open "your connection string"
    Set mobjCmd = New ADODB.Command
    With mobjCmd
        .ActiveConnection = mobjConn 
        .CommandText = "your stored procedure"
        .CommandType = adCmdStoredProc
        .CommandTimeout = 0
        .Parameters.Append .CreateParameter("your parameter name", adInteger, adParamInput, , your parameter value)
        ' repeat as many times as you have parameters
    
        .Execute
    End With
    

    To get your connection string, you can use the line

    Debug.Print CurrentDb.TableDefs("tblInstrumentInterfaceLog").Connect
    

    in the Immediate Window and that should show you a connection string which you can use.

    Would you try that and let me know if you have any problems.

    Ash

    0 讨论(0)
  • 2020-12-01 13:49

    Can also formulate a stored proc call that returns a result set as a select statement.

    As per this example:

    Sub Macro2()
    
    
    '
    ' Macro1 Macro
    '
        'Declare variables'
            Dim mySql As String
            Set objMyConn = New ADODB.Connection
            objMyConn.CommandTimeout = 0
            Set objMyCmd = New ADODB.Command
            objMyCmd.CommandTimeout = 0
            Set objMyRecordset = New ADODB.Recordset
            objMyConn.ConnectionString = CStr(Range("ADOConnectString").Value)
            objMyConn.Open
            Set objMyRecordset.ActiveConnection = objMyConn
            Set objMyCmd.ActiveConnection = objMyConn
    
    
       ' call dbo.TotalLHCLoadingRate  Range("TotalLHCLoadingRate")
    
            mySql = "select dbo.TotalLHCLoadingRate ( " _
        + CStr(Range("MemberNo").Value) _
        + ", getdate() ) "
            MsgBox "TotalLHCLoadingRate SQL : " + mySql
            objMyCmd.CommandText = mySql
            objMyCmd.CommandType = adCmdText
            objMyCmd.Execute
            objMyRecordset.Open objMyCmd
            Range("TotalLHCLoadingRate ").Value = ""
            Range("TotalLHCLoadingRate ").CopyFromRecordset (objMyRecordset)
            Range("TotalLHCLoadingRate ").Interior.ColorIndex = 37
            MsgBox "TotalLHCLoadingRate  : " + CStr(Range("TotalLHCLoadingRate ").Value)
            objMyRecordset.Close
    End Sub
    
    0 讨论(0)
提交回复
热议问题