Microsoft Office Tutorials and References
In Depth Information
Basic Error Handling
Basic Error Handling
When VBA code executes, a number of errors can occur. You can write code to
specify how these errors are handled. In some cases, you can safely ignore any
errors that occur within your procedures. To force VBA to ignore errors, use the
following statement:
On Error Resume Next
The following procedure attempts to delete a chart named Old Chart. If that chart
doesn’t exist, an error will occur. Using the On Error statement causes VBA to
ignore that inconsequential error and not display an error message.
Sub DeleteCharts()
On Error Resume Next
ActiveSheet.ChartObjects(“Old Chart”).Delete
End Sub
In other cases, you want your code to know whether errors occurred and then do
something about them. You can determine whether an error occurred by checking
the Number property of the Err object. If this property is equal to zero, an error did
not occur. If Err.Number is equal to anything else, an error did occur.
The following procedure attempts to activate Chart 1. If Chart 1 does not exist,
Err.Number will be something other than zero and a message will be displayed.
Sub ActivateTheChart()
On Error Resume Next
ActiveSheet.ChartObjects(“Chart 1”).Activate
If Err.Number <> 0 Then MsgBox “Chart does not exist”
End Sub
You can also specify that code execution continue at a different location when
an error occurs. The following procedure uses an On Error statement that points to
a code label called BailOut . If any error occurs in the procedure, execution stops
and the code after the BailOut statement is executed.
Sub ActivateTheChart()
On Error GoTo BailOut
ActiveSheet.ChartObjects(“Chart 1”).Activate
‘Other code goes here
Exit Sub
BailOut:
MsgBox “Cannot continue”
End Sub
Search JabSto ::




Custom Search