I made this test project, this is my standard module level code
' Declare a module-level variable to store the Application object
Public App As Application
' Procedure to initialize the App variable:
Sub StartAppEvents()
Set App = Application
End Sub
and this code on ThisWorkBook
Private Sub Workbook_Open()
StartAppEvents
End Sub
Private Sub App_WorkbookSheetChange(ByVal Wb As Workbook, ByVal Sh As Object, ByVal Target As Range)
MsgBox "App_WorksheetChange"
End Sub
Than I open new empty book and add this XLAM Add-in to new workbook
Nothing happens, Events in XLAM Add-in not connected to new Workbook.
Why? What I doing wrong?
UPD: If we adding WithEvents to App declaration - we need to move code to Class1 (Excel don't allow to use Withevents in standard modules). In this case we will receive another error:
What we need more? I see only two opportunity - add Public keyword to StartAppEvents declaration and change Instancing parameters from standard value (Private) to PublicNotCreatable. Both changing do not fix this error.
UPD2. Unfortunately idea from Tim Williams with New Events object don't working:
Public App As Application
should be
Public WithEvents App As Application
and it can't be in a regular code module: it needs to be in an object module such as a Class, Worksheet or maybe ThisWorkbook.
For example this pops up a msgbox whenever I edit a sheet
ThisWorkbook:
Option Explicit
Private AppEvt As AppEvents
Private Sub Workbook_Open()
Set AppEvt = New AppEvents
Set AppEvt.App = Application
End Sub
Class module (insert a new class module and change its name to AppEvents
):
Option Explicit
Public WithEvents App As Excel.Application
'there's no "workbooksheetchange" event....
Private Sub App_SheetChange(ByVal Sh As Object, ByVal Target As Range)
MsgBox "App_WorksheetChange"
End Sub
To make sure you're using a valid Application event, first select App
from the left-hand drop-down at the top of the class module, then select an available event from the right-hand drop-down.