How It Works

The CalculateSalesTax function has a declaration containing two variables as parameters. It uses Currency as the return data type.

Figure 2.19



? c2lculat.e3ale3t.2ji (5 . 0,

. 05}



Figure 2.20

Function CalculateSalesTax(curPrice As Currency, intTaxRate As Double) As Currency

A variable is declared to store the calculated tax value.

'declare variable for storing calculated tax Dim dblTaxAmt As Currency

The amount of tax is calculated by multiplying the curPrice value by the intTaxRate value.

'calculate amt of tax based on price and rate dblTaxAmt = curPrice * intTaxRate

Because the procedure is a function procedure, a particular value should be returned. In this case, it is desirable to return the amount of sales tax that was calculated. The name of the function is assigned to the dblTaxAmt value. This, in effect, returns the dblTaxAmt value to the calling procedure for further use and processing.

'return the calculated amt CalculateSalesTax = dblTaxAmt

When the function procedure was tested using the Immediate Window, the preceding code was executed using the values 5.0 and .05 you specified as the parameters. The value of 5.0 was assigned to the curPrice variable, and the value of .05 was assigned to the intTaxRate variable. The result of 0.25 was then displayed as the result.

Did you happen to notice that this time you had to use a question mark and put the parameters in parentheses? The prior examples did not use the question mark and parenthesis when calling sub procedures from the Immediate Window. As you just learned, the syntax differs slightly depending on whether you want to call a sub procedure or function from the Immediate Window.

Call a Function from another Procedure

Just like sub procedures, functions can be called from other procedures. The procedures you follow are basically the same as described in the prior example that illustrates calling a sub procedure from another sub procedure. The main difference is that when you call a function from another function or sub procedure, you typically assign the return value of the function to a local variable and then use it appropriately. For example, to call the CalculateSalesTax function from within another function or sub procedure, you could use the following code:

Dim dblSalesTax As Double

'call the CalculateSalesTax function and assign the result to the local variable dblSalesTax = CalculateSalesTax(100,.0 6)

Calling a Function from an Event

Again, just as with sub procedures, you can call a function from a class module associated with a form or report. The procedures are basically the same as described in the prior example that illustrates calling a sub procedure from an event. A more detailed explanation of events can be found in Chapter 3.

0 0

Post a comment