18.11.2014 Views

Microsoft Office

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

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

Part VI<br />

Programming Excel with VBA<br />

A function with two arguments<br />

This example builds on the previous one. Imagine that the sales manager implements a new policy: The<br />

total commission paid is increased by 1 percent for every year that the salesperson has been with the company.<br />

For this example, the custom Commission function (defined in the preceding section) has been<br />

modified so that it takes two arguments, both of which are required arguments. Call this new function<br />

Commission2:<br />

Function Commission2(Sales, Years)<br />

‘ Calculates sales commissions based on years in service<br />

Tier1 = 0.08<br />

Tier2 = 0.105<br />

Tier3 = 0.12<br />

Tier4 = 0.14<br />

Select Case Sales<br />

Case 0 To 9999.99<br />

Commission2 = Sales * Tier1<br />

Case 1000 To 19999.99<br />

Commission2 = Sales * Tier2<br />

Case 20000 To 39999.99<br />

Commission2 = Sales * Tier3<br />

Case Is >= 40000<br />

Commission2 = Sales * Tier4<br />

End Select<br />

Commission2 = Commission2 + (Commission2 * Years / 100)<br />

End Function<br />

The modification was quite simple. The second argument (Years) was added to the Function statement,<br />

and an additional computation was included that adjusts the commission before exiting the function.<br />

The following is an example of how you write a formula by using this function. It assumes that the sales<br />

amount is in cell A1, and that the number of years that the salesperson has worked is in cell B1.<br />

=Commission2(A1,B1)<br />

A function with a range argument<br />

The example in this section demonstrates how to use a worksheet range as an argument. Actually, it’s not at<br />

all tricky; Excel takes care of the details behind the scenes.<br />

Assume that you want to calculate the average of the five largest values in a range named Data. Excel doesn’t<br />

have a function that can do this calculation, so you can write the following formula:<br />

=(LARGE(Data,1)+LARGE(Data,2)+LARGE(Data,3)+<br />

LARGE(Data,4)+LARGE(Data,5))/5<br />

This formula uses Excel’s LARGE function, which returns the nth largest value in a range. The preceding formula<br />

adds the five largest values in the range named Data and then divides the result by 5. The formula<br />

works fine, but it’s rather unwieldy. And, what if you need to compute the average of the top six values?<br />

You’d need to rewrite the formula and make sure that all copies of the formula also get updated.<br />

710

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

Saved successfully!

Ooh no, something went wrong!