Home > OS >  Executing an SQL Server stored procedure using VBA in Excel and passing a variable
Executing an SQL Server stored procedure using VBA in Excel and passing a variable

Time:11-18

I am trying to execute an SQL Server stored procedure using VBA in Excel whilst passing a stored procedure.

My stored procedure code is as follows:

update [ASHCOURT_Weighsoft5].[dbo].[Invoice] set Is3rdPartyPosted = 0 where DocumentId = @document_no

My VBA Code is as follows:

Sub reverse_posted()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim Rs As ADODB.Recordset
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set Rs = New ADODB.Recordset
Dim i As Long
i = InputBox("Invoice Number to be re-posted")
con.Open "Provider=SQLOLEDB;Data Source=ashcourt_app1;Initial Catalog=ASHCOURT_Weighsoft5;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
cmd.CommandText = "ashcourt_balfour_reverse_posting" & i
Set Rs = cmd.Execute(, , adCmdStoredProc)
Rs.Close
Set Rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub

My VBA is very rusty so apologies. Essentially I am trying to pass the contents of the i variable to the parameter @document_no in the stored procedure.

Thanks in advance

CodePudding user response:

Add a parameter to the command

Option Explicit

Sub reverse_posted()

    Const PROC = "ashcourt_balfour_reverse_posting"

    Dim con As ADODB.Connection, cmd As ADODB.Command, i As Long
    i = InputBox("Invoice Number to be re-posted")
     
    Set con = New ADODB.Connection
    con.Open "Provider=SQLOLEDB;Data Source=ashcourt_app1;" & _
             "Initial Catalog=ASHCOURT_Weighsoft5;" & _
             "Integrated Security=SSPI;Trusted_Connection=Yes;"
    
    Set cmd = New ADODB.Command
    With cmd
        .ActiveConnection = con
        .CommandType = adCmdStoredProc
        .CommandText = PROC
        .Parameters.Append .CreateParameter("P1", adInteger, adParamInput)
        .Execute , i
    End With

    con.Close
    Set con = Nothing
End Sub
  • Related