Resume Execution If An Error Is Encountered

You can instruct VBA to continue execution of a procedure when it encounters an error using the On Error Resume Next statement. With this statement, VBA skips any runtime errors that occur during the execution of the procedure and execution continues with the next line of code. By doing this, the procedure continues executing and an error message does not inadvertently display on the screen. Keep in mind, that although the error message no longer displays, an error still exists in the code and therefore the procedure typically does not produce the appropriate results.

You should consider placing the On Error Resume Next statement at the top of all procedures you develop, especially procedures that you use in macros that you intend to distribute to another user. The statement ensures that the macro does not stop abruptly due to an error encountered in the code. If you adequately code to trap any potential errors, you can inform the user anytime conditions exist that would cause an error.

RESUME EXECUTION IF AN ERROR IS ENCOUNTERED

If you want to execute specific code when an error is encountered, you can modify the On Error statement to be On Error GoTo Label. With this statement, control jumps to a labeled section of code within the procedure whenever an error condition is encountered. Typically this code is placed at the end of the procedure. You may want to place an Exit Sub prior to the labeled section to keep the procedure from executing the code within the label if an error is not encountered.

For example, you can use ErrCode: as a label for the code to run if an error is encountered. Notice that the code label contains a colon. If you add the Resume Next statement at the end of the code, control returns to the next line of code in the procedure after the location that produced the runtime error. Although the runtime error appears to have been ignored, it is not. The information about the runtime error is placed in the Err object.

RESUME EXECUTION IF AN ERROR IS ENCOUNTERED

LQ Create a new subroutine.

0 Type On Error GoTo Label, replacing Label with the label for the code to execute when an error occurs.

0 Type the VBA code for the procedure.

■ The Exit Sub statement causes the procedure to exit without running the error code.

LQ Create a new subroutine.

Note: See Chapter 3 for information on creating subroutines.

0 Type On Error GoTo Label, replacing Label with the label for the code to execute when an error occurs.

0 Type the VBA code for the procedure.

—Q Type Exit Sub at the end of the main procedure code.

■ The Exit Sub statement causes the procedure to exit without running the error code.

0 0

Responses

  • hagos
    How to resume vba code if error is encountered?
    4 months ago

Post a comment