By Hemanta Sundaray on 2021-12-19
A VBA procedure can throw two kinds of errors:
Note: For error-handling procedures to work, the
Break on All Errorssetting must be turned off. In VBE, choose tools > Options and click the General tab in the Options dialogue box. IfBreak on All Errorsis selected, VBA ignores your error-handling code. You will usually want to use theBreak on Unhandled Errorsoption.
Normally, a run-time error causes VBA to stop and the user sees a dialogue box that displays the error number and a description of the error.
For example, execution of the following sub procedure displays an error message, because no cell in the current range selection contains a formula.
Sub SelectFormula()
ActiveCell.CurrentRegion.Select
Selection.SpecialCells(xlFormulas).Select
End Sub
The error message:
Whenever an error occurs, one of the options we have is to ignore the error and let VBA continue. We can do so by using the following statement:
On Error Resume Next
We can rewrite our Sub procedure above using the On Error Resume Next statement to prevent the error message from appearing:
Sub SelectFormula()
On Error Resume Next
ActiveCell.CurrentRegion.Select
Selection.SpecialCells(xlFormulas).Select
On Error GoTo 0
End Sub
The On Error GoTo 0 statement restores normal error handling for the remaining statements in the procedure.