我是VBA的新手,我尝试使用以下代码触发BeforeRefresh和AfterRefresh事件:
在名为clsQuery的类模块下,我有:
Option Explicit
Public WithEvents MyQuery As QueryTable
Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean)
If Success Then MsgBox "Query has been refreshed."
End Sub
Private Sub MyQuery_BeforeRefresh(Cancel As Boolean)
If MsgBox("Refresh query?", vbYesNo) = vbNo Then Cancel = True
End Sub
然后在模块下,我有:
Option Explicit
Dim colQueries As New Collection
Sub InitializeQueries()
Dim clsQ As clsQuery
Dim WS As Worksheet
Dim QT As QueryTable
For Each WS In ThisWorkbook.Worksheets
For Each QT In WS.QueryTables
Set clsQ = New clsQuery
Set clsQ.MyQuery = QT
colQueries.Add clsQ
Next QT
Next WS
MsgBox ("Works")
End Sub
最后,在Microsoft Excel Objects下,我有一个名为ThisWorkbook的选项卡:
Option Explicit
Dim colQueries As New Collection
Sub InitializeQueries()
Dim clsQ As clsQuery
Dim WS As Worksheet
Dim QT As QueryTable
For Each WS In ThisWorkbook.Worksheets
For Each QT In WS.QueryTables
Set clsQ = New clsQuery
Set clsQ.MyQuery = QT
colQueries.Add clsQ
Next QT
Next WS
MsgBox ("Works")
End Sub
因此,当我第一次打开excel文件时,消息框出现并说“" Works"”。但是,当我尝试刷新数据时,刷新前和刷新后的消息框不会出现。任何帮助将不胜感激!