最终,我希望在任何人刷新工作簿之后运行一个宏,特别是使用Excel中“数据”选项卡下的“刷新”按钮。但是,暂时,只要按下Refresh按钮就可以触发BeforeRefresh或AfterRefresh QueryTable事件。
除了'文档'在Microsoft开发中心网站上提供,我在此研究过程中阅读的相关帖子包括:
我显然缺少一些重要的东西(很可能很明显)。以下是我到目前为止的情况:
在类模块(qtclass)下
Option Explicit
Private WithEvents qt As Excel.QueryTable
Private Sub qt_AfterRefresh(ByVal Success As Boolean)
MsgBox "qt_AfterRefresh called sucessfully."
If Success = True Then
Call Module2.SlicePivTbl
MsgBox "If called succesfully."
End If
End Sub
Private Sub qt_BeforeRefresh(Cancel As Boolean)
MsgBox "qt_BeforeRefresh called."
End Sub
在ThisWorkbook模块下
Private Sub Workbook_Open()
Dim qtevent As qtclass
Dim qt As QueryTable
Set qt = ThisWorkbook.Worksheets("Data-Fund").ListObjects(1).QueryTable
Set qtevent = New qtclass
End Sub
我也尝试过特定工作表下的第二个代码块的变体,但还没有找到有用的东西。我是否需要在Worksheet模块中以某种方式调暗有问题的QueryTable?对于我所缺少的任何建议或想法将不胜感激。
答案 0 :(得分:13)
您还没有将查询表实际连接到类实例。 修订了qtclass
Option Explicit
Private WithEvents qt As Excel.QueryTable
Public Property Set HookedTable(q As Excel.QueryTable)
Set qt = q
End Property
Private Sub qt_AfterRefresh(ByVal Success As Boolean)
MsgBox "qt_AfterRefresh called sucessfully."
If Success = True Then
Call Module2.SlicePivTbl
MsgBox "If called succesfully."
End If
End Sub
Private Sub qt_BeforeRefresh(Cancel As Boolean)
MsgBox "qt_BeforeRefresh called."
End Sub
新的ThisWorkbook代码:
Dim qtevent As qtclass
Private Sub Workbook_Open()
Set qtevent = New qtclass
Set qtevent.HookedTable = ThisWorkbook.Worksheets("Data-Fund").ListObjects(1).QueryTable
End Sub
请注意,这是非常紧密耦合的。如果你要在类中引发事件并声明你的qtevent变量WithEvents,那么它将更加可重用。
答案 1 :(得分:0)
来源:https://www.excelandaccess.com/create-beforeafter-query-update-events/
班级:
注意:类名= clsQuery
Option Explicit
Public WithEvents MyQuery As QueryTable
Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean)
If Success Then
Debug.Print "After ReFresh"
End If
End Sub
Private Sub MyQuery_BeforeRefresh(Cancel As Boolean)
Debug.Print "Before ReFresh"
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
End Sub
ThisWorkbook.Event:
Private Sub Workbook_Open()
Call InitializeQueries
End Sub