在Excel中使用VBA执行SQL Server存储过程并传递变量



在传递存储过程时,我正尝试使用Excel中的VBA执行SQL Server存储过程。

我的存储过程代码如下:

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

最新更新