使用adAsyncExecute参数未触发ExecuteComplete ADODB Connection事件

时间:2013-04-23 10:51:46

标签: events excel-vba event-handling ado vba

我在尝试异步捕获存储过程执行时遇到问题。

在我的代码VBA下面(在名为clsAsync的类模块中):

Option Explicit

Private WithEvents cnn As ADODB.Connection


Private Sub cnn_ExecuteComplete(ByVal RecordsAffected As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pCommand As ADODB.Command, ByVal pRecordset As ADODB.Recordset, ByVal pConnection As ADODB.Connection)
    MsgBox "Execution completed"
End Sub

Sub execSPAsync()
    Set cnn = New ADODB.Connection
    Set rst = New ADODB.Recordset
    cnn.ConnectionString = "connection to my database SQLSEREVER"
    cnn.Open
    cnn.Execute "kp.sp_WaitFor", adExecuteNoRecords, adAsyncExecute
End Sub

此类为PublicNotCreatable。

要从模块调用sub execSPAsync,我使用以下代码:

Sub testASYNC()
    Dim a As New clsAsync
    Call a.execSPAsync
End Sub

存储过程非常简单:

alter PROC kp.sp_WaitFor
AS

WAITFOR DELAY '00:00:05'

我的问题是事件ExecuteComplete根本没有被触发,而如果我评论adAsynExecute参数一切正常。 如何解决我的问题?

1 个答案:

答案 0 :(得分:3)

我解决了替换调用代码的问题:

Sub testASYNC()
    Dim a As New clsAsync
    Call a.execSPAsync
End Sub

使用这个新代码:

Private a As clsAsync

Sub testASYNC()
    Set a = New clsAsync
    Call a.execSPAsync
End Sub

在异步模式下,对象“a”在过程结束时不再可用(范围可见性问题)。