Microsoft Office Tutorials and References
In Depth Information
Controlling Execution
In many cases, you can ignore error handling within your functions. If the user does not provide
the proper number of arguments, the function simply returns an error value. It’s up to the user to
figure out the problem. In fact, this is how Excel’s worksheet functions handle errors.
In other cases, you want your code to know if errors occurred and then do something about
them. Excel’s On Error statement enables you to identify and handle errors.
To simply ignore an error, use the following statement:
On Error Resume Next
If you use this statement, you can determine whether an error occurs 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 example is a function that returns the name of a cell or range. If the cell or range
does not have a name, an error occurs, and the formula that uses the function returns a #VALUE!
Function RANGENAME(rng)
RANGENAME = rng.Name.Name
End Function
The following list shows an improved version of the function. The On Error Resume Next
statement causes VBA to ignore the error. The If Err statement checks whether an error occurs.
If so, the function returns an empty string.
Function RANGENAME(rng)
On Error Resume Next
RANGENAME = rng.Name.Name
If Err.Number <> 0 Then RANGENAME = “”
End Function
The following statement instructs VBA to watch for errors; if an error occurs, it continues
executing at a different named location — in this case, a statement labeled ErrHandler :
On Error GoTo ErrHandler
The following Function procedure demonstrates this statement. The DIVIDETWO function
accepts two arguments ( num1 and num2 ) and returns the result of num1 divided by num2 .
Search JabSto ::

Custom Search