问题
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