I am going to show a MessageBox before save workbook. I have tried with event handler Sub App_WorkbookBeforeSave() and Sub Workbook_BeforeSave but both doesn’t work! Why?
There are my Sub in addin:
Private Sub App_WorkbookBeforeSave(ByVal Wb As Workbook, _
ByVal SaveAsUI As Boolean, Cancel As Boolean)
MsgBox "Good bye! Data is save."
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
MsgBox "Good bye! Data is save."
End Sub
UPDATE
I was put them in ThisWorkbook modules belong to Microsoft Excel Objects
This kind of functionality requires…
Either way, you need to create an instance of a WithEvents Application object which, while you don’t touch the object directly after you create it, enables the events to be captured.
I like the second option (cleaner, makes you look like a boss, etc.). Create a class and call it something. I like to call my class ImAGoodListener. In the class, include the appropriate Subs for any application events you want to use
With the arguments, you can do cool and mischievous things like prevent the workbook from being saved…
(I like On Error Resume Next for this so we don’t risk not allowing a user to save his/her workbook should our code go haywire)
In the ThisWorkbook module put something like this…
This will start the event listening when your Add-In is initially opened.
Alternatively, if you’re using CustomUI for the ribbon, you use a Ribbon Onload event to trigger the start of listening (I do this when my events are used primarily for ribbon behavior so I can easy disable listening in the CustomUI xml).
Some other application events of use are:
Here’s a list of all events, but note that some of them are workbook (event handlers start with Workbook_ events which won’t work for this sort of thing.
Chip goes into great detail about these sort of events on his site here.