Tag Archives: VB application

On error goto (resume)

Iamlaosong article
Error capture is often used to prevent unexpected program interruptions. There are three types of capture:
On Error GoTo 0
means to disable any Error handlers that have been started in the current process. The test results show that -1 actually works, which has the same effect as 0. After executing this statement, if the error is encountered again, the system will interrupt the program execution and pop up an error prompt.

On Error Resume Next
indicates that when a runtime Error occurs, the control goes to the statement that follows the Error and continues to run here. That is, no error prompt, continue to run. Use this form when accessing objects instead of using On Error GoTo.

On Error GoTo line
starts the Error handler, and the routine starts with the line specified in the necessary line parameter. The line parameter can be any line label or line number. If a runtime error occurs, the control jumps to line, activating the error handler. Using this kind of statement is to write your own error handlers, especially for predictable errors. The specified line must be in a procedure, the same as the On Error statement; Otherwise, a compile time error will occur. After you go to line, you can do error handling. In addition to the Exit Sub, the error handler can finally execute:

Resume: Execute at the wrong place. Try again. Resume Next: Similar to On Error Resume Next, ignore the current Error statement and execute the Next statement Resume < Label & gt; Go to the label and deal with it.

Err.Clear is used to Clear the Err object after handling errors; for example, Clear is used when using delay Error handling for On Error Resume Next. The Clear method is automatically called whenever the following statement is executed:
Resume statement of any type Exit Sub, Exit Function, Exit Property any On Error statement.

You can see the effect of the error capture statement with the following routine (assuming no more than 4 worksheets) :

Sub tt()
    For i = 0 To 5
       On Error GoTo err1
       a = 5
       b = a/i
       MsgBox b
       On Error GoTo err2
       c = i
       Sheets(c).Select
    Next i
    Exit Sub
err1:
    MsgBox err.Number & err.Description
    err.Clear
    MsgBox err.Number & err.Description
    Resume Next
err2:
    MsgBox err.Number & err.Description
    c = 1
    Resume
End Sub

Sub tt()
    For i = 0 To 5
       On Error GoTo err1
       a = 5
       b = a/i
       MsgBox b
       On Error GoTo err2
       c = i
       Sheets(c).Select
    Next i
    On Error GoTo 0
    Sheets(i).Select
    Exit Sub
err1:
    MsgBox err.Number & err.Description
    err.Clear
    MsgBox err.Number & err.Description
    Resume Next
err2:
    MsgBox err.Number & err.Description
    c = 1
    Resume
End Sub