excelvbamsdn

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


Can anyone find the difference between 'On error goto -1' and 'on error goto 0' in VBA? I've tried google and msdn, but I've had no luck.


Solution

  • 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