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

前端 未结 3 1792
有刺的猬
有刺的猬 2020-11-27 12:55

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.

3条回答
  •  没有蜡笔的小新
    2020-11-27 13:28

    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
    

提交回复
热议问题