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 25: VBA Custom Function Examples 709<br />

Custom functions that you develop in VBA can also have optional arguments. You specify an<br />

optional argument by preceding the argument’s name with the keyword Optional. The following<br />

is a simple function that returns the user’s name:<br />

Function USER()<br />

USER = Application.UserName<br />

End Function<br />

Suppose that in some cases, you want the user’s name to be returned in uppercase letters. The<br />

following function uses an optional argument:<br />

Function USER(Optional UpperCase As Variant) As String<br />

If IsMissing(UpperCase) Then UpperCase = False<br />

If UpperCase = True Then<br />

USER = Ucase(Application.UserName)<br />

Else<br />

USER = Application.UserName<br />

End If<br />

End Function<br />

If you need to determine whether an optional argument was passed to a function,<br />

you must declare the optional argument as a variant data type. Then you can use the<br />

IsMissing function within the procedure, as demonstrated in this example.<br />

If the argument is FALSE or omitted, the user’s name is returned without any changes. If the<br />

argument is TRUE, the user’s name converts to uppercase (using the VBA Ucase function)<br />

before it is returned. Notice that the first statement in the procedure uses the VBA IsMissing<br />

function to determine whether the argument was supplied. If the argument is missing, the statement<br />

sets the UpperCase variable to FALSE (the default value).<br />

Optional arguments also allow you to specify a default value in the declaration, rather than testing<br />

it with the IsMissing function. The preceding function can be rewritten in this alternate<br />

syntax as<br />

Function USER(Optional UpperCase As Boolean = False) As String<br />

If UpperCase = True Then<br />

USER = UCase(Application.UserName)<br />

Else<br />

USER = Application.UserName<br />

End If<br />

End Function

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

Saved successfully!

Ooh no, something went wrong!