The On Error Resume Next Statement

The syntax:

On Error Resume Next tells VBA to continue executing the code immediately following the line that caused the error. There are two important uses for this form of On Error. The first is to cause VBA to ignore an error. For instance, the code:

Sub example()

On Error Resume Next MsgBox Selection.Cells.Count End Sub will report the cell count when the selection is a worksheet range and do nothing when the selection is not a worksheet range.

Another important use for the On Error Resume Next syntax is for in-line error checking, where we check for errors immediately following the line that may have caused an error. For instance, another way to handle errors in the previous example is:

Sub example()

On Error Resume Next MsgBox Selection.Cells.Count If Err.Number <> 0 Then

MsgBox Err.Description, vbCritical End If End Sub

0 0

Post a comment