简体   繁体   中英

Excel VBA executing SQL Server stored procedure - result set throwing error 3704

I am trying to execute a SQL Server stored procedure from Excel VBA. The procedure returns rows into a result set object. However, while running the code, it throws an error:

3704 Operation is not allowed when the object is closed

Note:
There is no problem with the database connection because Select query running on the same connection object are working fine.

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rst As New ADODB.Recordset

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
ThisWorkbook.initialize
cn.Provider = "sqloledb"
cn.Properties("Data Source").Value = ThisWorkbook.server
cn.Properties("Initial Catalog").Value = ThisWorkbook.db
cn.Properties("User ID").Value = "xxxxx"
cn.Properties("Password").Value = "xxxxx"
cn.Open

Set cmd = New ADODB.Command
cmd.CommandText = "Generate_KPI_Process_Quality_Check_RunTime"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = cn

Set prm = cmd.CreateParameter("@currentMonth", adChar, adParamInput, 255, cmb_month.Value)
cmd.Parameters.Append prm

Set prm = cmd.CreateParameter("@center", adChar, adParamInput, 255, cmb_center.Value)
cmd.Parameters.Append prm

rst.CursorType = adOpenStatic
rst.CursorLocation = adUseClient
rst.CursorLocation = adUseServer
rst.LockType = adLockOptimistic

rst.Open cmd

If (rst.BOF And rst.EOF) Then
'Some Code
End If

Put

SET NOCOUNT ON

in the stored procedure -- this will prevent output text generation like "1 record(s) updated".

You have to provide more parameters for the Open method of Recordset Object

try rst.Open cmd, cn

Use the Set keyword to assign the object:

Set cmd.ActiveConnection = cn

otherwise, the default property of the Connection object (which happen to be the connection string) will be assigned in lieu of the Connection object itself.

Just put another recordset that will contain resultsets

Dim rst1 As New ADODB.Recordset
SET rst1=rst.NextRecordset 'this will return the first resultset

If rst1.BOF or rst1.EOF Then...
    'some code
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM