11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 25: VBA Custom Function Examples 711<br />

Function SIMPLESUM(ParamArray arglist() As Variant) As Double<br />

Dim arg as Variant<br />

For Each arg In arglist<br />

SIMPLESUM = SIMPLESUM + arg<br />

Next arg<br />

End Function<br />

The following formula returns the sum of the single-cell arguments:<br />

=SIMPLESUM(A1,A5,12)<br />

The most serious limitation of the SIMPLESUM function is that it does not handle multicell<br />

ranges. This improved version does:<br />

Function SIMPLESUM(ParamArray arglist() As Variant) As Double<br />

Dim arg as Variant<br />

Dim cell as Range<br />

For Each arg In arglist<br />

If TypeName(arg) = “Range” Then<br />

For Each cell In arg<br />

SIMPLESUM = SIMPLESUM + cell.Value<br />

Next cell<br />

Else<br />

SIMPLESUM = SIMPLESUM + arg<br />

End If<br />

Next arg<br />

End Function<br />

This function checks each entry in the Arglist array. If the entry is a range, then the code uses<br />

a For Each-Next loop to sum the cells in the range.<br />

Even this improved version is certainly no substitute for the Excel SUM function. Try it by using<br />

various types of arguments, and you’ll see that it fails unless each argument is a value or a range<br />

reference. Also, if an argument consists of an entire column, you’ll find that the function is very<br />

slow because it evaluates every cell — even the empty ones.<br />

Emulating the Excel SUM function<br />

This section presents a Function procedure called MYSUM. Unlike the SIMPLESUM function<br />

listed in the previous section, MYSUM emulates the Excel SUM function perfectly.<br />

Before you look at the code for the MYSUM function, take a minute to think about the Excel SUM<br />

function. This very versatile function can have any number of arguments (even missing arguments),

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

Saved successfully!

Ooh no, something went wrong!