避免在 aa 加载项 (xlam) 中重复执行应用程序级事件

Avoid double execution of application level events in aa add-in (xlam)

我有一个 xlam 可以在工作簿的打开和关闭时工作。

为了做到这一点,我用下一个代码创建了一个 class 模块:

''''''''''''''''''''''' Setup Event '''''''''''''''''''''''''''''''''''''''''''''''''

Public WithEvents appevent As Application

''''''''''''''''''''''' Setup Application at Close''''''''''''''''''''''''''''''''''''''''''''

Private Sub appevent_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)

    MsgBox("The workbook " & Wb.Name & " will close now")

End Sub

''''''''''''''''''''''' Setup Application at Open''''''''''''''''''''''''''''''''''''''''''''

Private Sub appevent_WorkbookOpen(ByVal Wb As Workbook)

     MsgBox("The workbook " & Wb.Name & " is now open")

End Sub

然后在 "ThisWorkbook" 对象中我有这个代码:

Dim myobject As New Class1

Sub Workbook_Open()

    Set myobject.appevent = Application

End Sub

安装外接程序后,每当打开文件时都会出现两个消息框,Excel 启动时出现一个,文件打开时出现一个,关闭时出现类似情况。

为什么会发生这种情况以及如何避免?

未经测试,但请尝试以下操作:

Private Sub appevent_WorkbookOpen(ByVal Wb As Workbook, Cancel As Boolean)

    If Wb Is ThisWorkbook Then Exit Sub  ' don't do anything when the add-in opens  
    MsgBox("The workbook " & Wb.Name & " is now open")

End Sub

appevent_WorkbookBeforeClose.

同样如此