Create and Call a New Function Procedure

So far, all the examples you have reviewed have dealt with creating and calling sub procedures. Earlier you learned that a function procedure is used to perform a particular action and also return a particular result. Let's look at that in more detail now.

The syntax for declaring a new function procedure without parameters is:

Function ProcedureName As DataType 'code for the function End Function

The syntax for a new sub procedure that contains variables as parameters is:

Function ProcedureName(Variables) As DataType 'code for the procedure End Function

Note that in both the preceding cases, the Function keyword is used instead of the Sub keyword in two places. Also note that a data type is required as part of the function declaration. The data type should be specified to correspond to the type of the value you want the function to output.

Now you can create a new function to illustrate these procedures.

Try It Out Creating the CalculateSalesTax Function

The CalculateSalesTax function you create next accepts a price and a tax rate as parameters and calculates the amount of tax.

1. In the modBusinessLogic standard module, add the following function, called CalculateSalesTax, after the FinalizeOrder sub procedure.

Function CalculateSalesTax(curPrice As Currency, intTaxRate As Double)

As Currency

'declare variable for storing calculated

tax

Dim dblTaxAmt As Currency

'calculate amt of tax based on price and

rate

dblTaxAmt = curPrice * intTaxRate

'return the calculated amt

CalculateSalesTax = dblTaxAmt

End Function

2. After the function has been added, the Visual Basic Editor window should look something like Figure 2.19.

3. Run the new function from the Immediate Window using the syntax shown in Figure 2.20 and press Enter. You can select View C> Immediate Window if it is not already displayed.

4. After you press Enter, the 0.25 value is displayed in the Immediate Window.

0 0

Post a comment