30.04.2017 Views

4523756273

Create successful ePaper yourself

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

Chapter 9: Using VBA and Worksheet Functions<br />

More about Using Worksheet Functions<br />

Newcomers to VBA often confuse VBA’s built-in functions and Excel’s workbook<br />

functions. A good rule to remember is that VBA doesn’t try to reinvent<br />

the wheel. For the most part, VBA doesn’t duplicate Excel worksheet functions.<br />

139<br />

For most worksheet functions that are unavailable as methods of the<br />

WorksheetFunction object, you can use an equivalent VBA built-in operator<br />

or function. For example, the MOD worksheet function is not available in the<br />

WorksheetFunction object because VBA has an equivalent, its built-in Mod<br />

operator.<br />

Bottom line? If you need to use a function, first determine whether VBA has<br />

something that meets your needs. If not, check out the worksheet functions. If<br />

all else fails, you may be able to write a custom function by using VBA.<br />

Using Custom Functions<br />

I’ve covered VBA functions and Excel worksheet functions. The third category<br />

of functions you can use in your VBA procedures is custom functions.<br />

A custom function (also known as User Defined Function, UDF) is one you<br />

develop yourself by using (what else?) VBA. To use a custom function, you<br />

must define it in the workbook in which you use it.<br />

Here’s an example of defining a simple Function procedure and then using it<br />

in a VBA Sub procedure:<br />

Function MultiplyTwo(num1, num2) As Double<br />

MultiplyTwo = num1 * num2<br />

End Function<br />

Sub ShowResult()<br />

Dim n1 As Double, n2 As Double<br />

Dim Result As Double<br />

n1 = 123<br />

n2 = 544<br />

Result = MultiplyTwo(n1, n2)<br />

MsgBox Result<br />

End Sub<br />

The custom function MultiplyTwo has two arguments. The ShowResult Sub<br />

procedure uses this Function procedure by passing two arguments to it (in<br />

parentheses). The ShowResult procedure then displays a message box showing<br />

the value returned by the MultiplyTwo function.

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

Saved successfully!

Ooh no, something went wrong!