11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 24: VBA Programming Concepts 657<br />

In many cases, you can ignore error handling within your functions. If the user does not provide<br />

the proper number of arguments, the function simply returns an error value. It’s up to the user to<br />

figure out the problem. In fact, this is how Excel’s worksheet functions handle errors.<br />

In other cases, you want your code to know if errors occurred and then do something about<br />

them. Excel’s On Error statement enables you to identify and handle errors.<br />

To simply ignore an error, use the following statement:<br />

On Error Resume Next<br />

If you use this statement, you can determine whether an error occurs by checking the Number<br />

property of the Err object. If this property is equal to zero, an error did not occur. If Err.<br />

Number is equal to anything else, an error did occur.<br />

The following example is a function that returns the name of a cell or range. If the cell or range<br />

does not have a name, an error occurs, and the formula that uses the function returns a #VALUE!<br />

error.<br />

Function RANGENAME(rng)<br />

RANGENAME = rng.Name.Name<br />

End Function<br />

The following list shows an improved version of the function. The On Error Resume Next<br />

statement causes VBA to ignore the error. The If Err statement checks whether an error occurs.<br />

If so, the function returns an empty string.<br />

Function RANGENAME(rng)<br />

On Error Resume Next<br />

RANGENAME = rng.Name.Name<br />

If Err.Number 0 Then RANGENAME = “”<br />

End Function<br />

The following statement instructs VBA to watch for errors; if an error occurs, it continues executing<br />

at a different named location — in this case, a statement labeled ErrHandler:<br />

On Error GoTo ErrHandler<br />

The following Function procedure demonstrates this statement. The DIVIDETWO function<br />

accepts two arguments (num1 and num2) and returns the result of num1 divided by num2.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!