Excel VBA 打开工作簿时实例化 AfterCalculate 事件处理程序

Excel VBA instantiate AfterCalculate event handler when opening workbook

我想处理 Excel 的 Application.AfterCalculate event

看来这只能使用 class 来完成。打开工作簿时如何定义和实例化此类事件处理程序?

将以下代码放入 ThisWorkbook 对象中。

Public WithEvents appEventHandler As Application

Private Sub Workbook_Open()
    Set appEventHandler = Application
End Sub

Private Sub appEventHandler_AfterCalculate()
    ' DO WHATEVER YOU WANT After Calculate.  E.g., call a Public Subroutine.
    MsgBox "AfterCalculate called"
End Sub

如果 AfterCalculate 处理程序修改了电子表格中的任何内容,那么为了防止意外的重复或递归回调,我将其包装在 If 语句中以确保它只运行一次,如以下模块所示代码:

Public RunningAfterCalculate As Boolean

Public Sub RunAfterCalculate()
    If Not RunningAfterCalculate Then
        RunningAfterCalculate = True
        ' DO WHATEVER YOU WANT AfterCalculate
        ' ...
        RunningAfterCalculate = False
    End If
End Sub

请注意,如果由于某种原因 VBA 遇到未处理的异常,您将不得不重置 appEventHandler – 例如通过 运行 像这样的子:

Public Sub RestartEventHandler()
    Set ThisWorkbook.appEventHandler = Application
    Application.EnableEvents = True  ' Just in case...
    RunningAfterCalculate = False
End Sub