在 Excel 中使用 VBA 执行 SQL 服务器存储过程并传递一个变量

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

我正在尝试在 Excel 中使用 VBA 执行 SQL 服务器存储过程,同时传递存储过程。

我的存储过程代码如下:

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

我的VBA代码如下:

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

我的 VBA 很生疏,所以很抱歉。本质上,我试图将 i 变量的内容传递给存储过程中的参数@document_no。

提前致谢

给命令添加一个参数

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