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

大憨熊 提交于 2020-02-25 04:08:52

问题


I have a xlam that works at open & close of the workbook.

In order to do this I've created a class module with the next code:

''''''''''''''''''''''' 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

Then in the "ThisWorkbook" object I have this code:

Dim myobject As New Class1

Sub Workbook_Open()

    Set myobject.appevent = Application

End Sub

After installing the Add-in, whenever a file opens two message box appear, one when Excel starts, then one once the file is open, similar case for close.

Why is this happening and How to avoid it?


回答1:


Untested, but try the following:

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

and similarly for appevent_WorkbookBeforeClose.



来源:https://stackoverflow.com/questions/60103405/avoid-double-execution-of-application-level-events-in-aa-add-in-xlam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!