Microsoft Office Tutorials and References
In Depth Information
7.5.5 The Resume Statement
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
7.5.5 The Resume Statement
It is also possible to include the Resume statement in the error-handling portion of the code. This
will cause VBA to resume execution at the line that follows the one that caused the error. Thus,
the previous code is equivalent to the following:
Sub example()
On Error GoTo ERR_EXAMPLE
MsgBox Selection.Cells.Count
Exit Sub
ERR_EXAMPLE:
MsgBox Err.Description, vbCritical
Resume Next
End Sub
There are three variations on the Resume statement:
Resume
Resume Next
Resume ALabel
The first version will cause VBA to resume with the line that caused the error. This is useful if
your error-handling code actually repairs the error condition and you want the line that caused the
original error to be executed again.
To illustrate, the procedure in Example 7-2 is designed to open a workbook named a:\test.xls . If it
does not exist, an error will occur. The error-handling code gives the user a chance to enter a new
workbook name, in which case we want to execute the Open method again. Hence the use of the
Resume statement.
Search JabSto ::




Custom Search