提问人:Darren Wardill 提问时间:11/17/2021 最后编辑:braXDarren Wardill 更新时间:11/17/2021 访问量:1799
在 Excel 中使用 VBA 执行 SQL Server 存储过程并传递变量
Executing an SQL Server stored procedure using VBA in Excel and passing a variable
问:
我正在尝试在传递存储过程时使用 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。
提前致谢
答:
1赞
CDP1802
11/17/2021
#1
向命令添加参数
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
评论
0赞
Darren Wardill
11/17/2021
太棒了,非常感谢你,这是一种享受。
评论
"ashcourt_balfour_reverse_posting " & i
在带引号的字符串内添加空格或使用参数cmd.CommandType = adCmdStoredProc
cmd.Execute