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.

702<br />

Part VI: Developing Custom Worksheet Functions<br />

Function REVERSETEXT(text As String) As String<br />

‘ Returns its argument, reversed<br />

REVERSETEXT = StrReverse(text)<br />

End Function<br />

This function reverses the contents of its single-cell argument (which can be text or a value). If<br />

the argument is a multicell range, the function returns #VALUE!<br />

Assume that you want this function to work only with strings. If the argument does not contain a<br />

string, you want the function to return an error value (#N/A). You may be tempted to simply<br />

assign a string that looks like an Excel formula error value. For example:<br />

REVERSETEXT = “#N/A”<br />

Although the string looks like an error value, it is not treated as such by other formulas that may<br />

reference it. To return a real error value from a function, use the VBA CVErr function, which converts<br />

an error number to a real error.<br />

Fortunately, VBA has built-in constants for the errors that you want to return from a custom<br />

function. These constants are listed here:<br />

xlErrDiv0<br />

xlErrNA<br />

xlErrName<br />

xlErrNull<br />

xlErrNum<br />

xlErrRef<br />

xlErrValue<br />

The following is the revised REVERSETEXT function:<br />

Function REVERSETEXT(text As Variant) As Variant<br />

‘ Returns its argument, reversed<br />

If WorksheetFunction.ISNONTEXT(text) Then<br />

REVERSETEXT = CVErr(xlErrNA)<br />

Else<br />

REVERSETEXT = StrReverse(text)<br />

End If<br />

End Function

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

Saved successfully!

Ooh no, something went wrong!