I use PERSONAL.XLSB to execute global macros. Within it, I also listen to application events by doing this in the ThisWorkbook
object:
Dim WithEvents app As Application
Private Sub Workbook_Open()
Set app = Application
End Sub
Now I can listen to all workbook events without having to wire up an event to each workbook.
The problem is that, whenever a macro throws an exception and causes me to have to End the macro, all global variables get nuked, so the app
variable gets set to Nothing
which causes all global events to no longer fire.
Is there some way I can have this variable automatically set back to an instance of Application
whenever it gets nulled out?
The Workbook_Open Event is automatically added to the module. This macro will run when the workbook is opened and macros are enabled. You can delete this event's code if you do not want to use it. Select another event from the Procedure's drop-down.
Insert VBA code to Excel Workbook Open your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.)
A workbook event is defined as an action that triggers the execution of a specific macro in Excel. VBA automatically executes an event once a user specifies the code for an event that has already occurred. An example of a VBA worksheet event is Open, which is triggered as soon as a Workbook is activated.
You can create a public function which contains the default values of all the global variable then call that function under your error handle. An example:
Dim WithEvents app As Application
Private Sub Workbook_Open()
On Error GoTo reset
Set app = Application
On Error Goto 0 ' Turn off error trapping.
Exit Sub
Reset:
Call resetvar
End Sub
Public Sub Resetvar()
Set app = Application
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With