Difference between 'on error goto 0' and 'on error goto -1' -- VBA

Solution 1:

On Error GoTo 0 disables any error trapping currently present in the procedure.

On Error GoTo -1 clears the error handling and sets it to nothing which allows you to create another error trap.

Example: On Error GoTo -1

After the first error is raised, it will GoTo ErrorFound which will then clear the routine's error handling and set a new one, which will GoTo AnotherErrorFound when an error is found.

Sub OnErrorGotoMinusOneTest()

    On Error GoTo ErrorFound

    Err.Raise Number:=9999, Description:="Forced Error"

    Exit Sub

ErrorFound:

    On Error GoTo -1 'Clear the current error handling
    On Error GoTo AnotherErrorFound 'Set a new one
    Err.Raise Number:=10000, Description:="Another Forced Error"

AnotherErrorFound:

    'Code here

End Sub

Example: On Error GoTo 0

After the first error is raised, you will receive the error as error handling has been disabled.

Sub OnErrorGotoZeroTest()

    On Error GoTo 0

    Err.Raise Number:=9999, Description:="Forced Error"

End Sub

Solution 2:

This answer addresses the confusion between the error object and the error handler.

The error object can be cleared using Err.Clear. This does not affect the error handler.

The error handler becomes enabled by using On Error Goto <label>. It becomes active when an error occurs.

While the error handler is active, you can not assign a new error handler. On Error Goto <label> will have no effect. VBA simply ignores the attempt to assign a new error handler.

Using Err.Clear does not cancel the error handler.

Jumping to a different place in the code using Goto <label> does not cancel the error handler. Using Goto <label> in an error handling block can cause confusion and should be avoided. You might think the error handler is no longer active when in fact it is still active.

The effect of an active error handler is that you can not assign a new error handler. On Error Goto <label> will have no effect. VBA simply ignores the attempt to assign a new error handler. Any additional errors will be unhandled while the error handler is active.

The only way to exit an active error handler is:

  1. Resume
  2. Resume Next
  3. Resume <label>
  4. On error goto -1
  5. exit the procedure

Using any one of these ways to exit the error handler will also clear the error object.

Excellent source: Pearson Error Handling In VBA Chip Pearson doesn't mention On error goto -1 in his article. To quote him:

I deliberately did not include On Error GoTo -1 because it serves no real purpose and can lock up the entire Excel application unless used in exactly the right way. Yes, On Error GoTo -1 is syntactically valid, but it is like giving a gun to drunk teenager. Nothing good will come from it.

You can also handle errors inline without using an error handler using the error object: MSDN Inline Error Handling