Search code examples
vbaonerror

Restoring Old VBA On Error


Let's say you have On Error Defined in your main sub.

Sub Main()

   On Error Goto CatchAll
   '... Some code... goes here
   Call XYZ



CatchAll:
   Msgbox "An Unexpected Error Occurred"
   End
End Sub

Within Main sub, you have a call to routine XYZ. Let's say that Sub XYZ is like this:

Sub XYZ()
   'If unexpected error happens here, control will be shifted to sub Main, Label CatchAll

   On Error Goto Errorz

   'If unexpected error happens here, control will be shifted to same sub, Label Errorz...

Errorz:
        Msgbox "You have crashed inside XYZ"
        End

End Sub

Note the comments entered in sub XYZ. Namely, where the control shifts after a program crash is experienced is based on the last "On Error Goto" statement.

Is there a way, in VBA, to restore the old On Error Goto?

In other words, within Sub XYZ, I have some code:

Sub XYZ()
   On Error Goto Errorz:

   'Some Code

   On Error Goto <Old Error Trapping Method>
   'Here I desire to go back to Main CatchAll: label.  Is there a way to do that?

End Sub

Note the last comment in the code above. I want to be able to redefine On Error to restore the last behavior of On error before I defined the new behavior (Last Behavior: Goto Main.CatchAll label, New behavior, Goto XYZ.Errorz label). I want to be able to, at this point in the code, say, On error Go to Main.CatchAll.

Is there some way to accomplish this?


Solution

  • Yes, in XYZ()

    On Error Goto 0
    

    should clear the current procedure's (i.e. XYZ()'s) error handler and in your example pass control of error handling to the error handler in Main().