Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel application events: How to automatically reset WithEvents variable after a runtime error?

Tags:

excel

events

vba

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?

like image 266
oscilatingcretin Avatar asked Sep 01 '16 13:09

oscilatingcretin


People also ask

Which event handling routine runs automatically when a workbook opens?

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.

How do I trigger VBA code in Excel?

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.)

What is a macro triggered event?

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.


1 Answers

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
like image 95
RAJA THEVAR Avatar answered Nov 15 '22 09:11

RAJA THEVAR