ibe*_*exy 2 excel vba stored-procedures excel-vba
我试图使用VBA从Excel运行存储过程,但我得到一个"类型不匹配"错误与以下代码.我可以执行带参数的存储过程作为传递给Command对象的字符串,如下所示吗?
Function Sproc()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim ConnectionString As String
Dim StrSproc As String
ConnectionString = "Provider=SQLOLEDB;Data Source=DBSource;" & _
"Initial Catalog=CurrentDb;" & _
"Integrated Security=SSPI;"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes
'before VBA times out, but your database might timeout before this value
cnn.CommandTimeout = 900
StrSproc = "EXEC StoredProcedure " & _
"@parameter1 = 0," & _
"@parameter2 = 0," & _
"@parameter3 = 0,"
Application.StatusBar = "Running stored procedure..."
Set rst = cmd.Execute(, , StrSproc)
End Function
Run Code Online (Sandbox Code Playgroud)
试试这个:
Option Explicit
Function Sproc()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim cnnStr As String
Dim Rs As New ADODB.Recordset
Dim StrSproc As String
cnnStr = "Provider=SQLOLEDB;Data Source=DBSource;" & "Initial Catalog=CurrentDb;" & _
"Integrated Security=SSPI;"
With cnn
.CommandTimeout = 900
.ConnectionString = cnnStr
.Open
End With
With cmd
.ActiveConnection = cnn
.CommandType = adCmdStoredProc
.CommandText = "[StoredProcedureName]"
.Parameters.Append .CreateParameter("@parameter1", adInteger, adParamInput, , 0)
.Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0)
.Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0)
End With
With Rs
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmd
End With
Application.StatusBar = "Running stored procedure..."
Set rst = cmd.Execute
End Function
Run Code Online (Sandbox Code Playgroud)