Specifying Argument Types

In the preceding section, you learned that functions perform some calculations based on data received through their arguments. When you declare a function procedure, you list the names of arguments inside a set of parentheses. Argument names are like variables. Each argument name refers to whatever value you provide at the time the function is called. When a subroutine calls a function procedure, it passes the required arguments as variables to it. Once the function does something, the result is assigned to the function name. Notice that the function procedure's name is used as if it were a variable.

Like variables, functions can have types. The result of your function procedure can be String, Integer, Long, etc. To specify the data type for your function's result, add the keyword As and the name of the desired data type to the end of the function declaration line. For example:

Function MultiplyIt(num1, num2) As Integer

If you don't specify the data type, Visual Basic assigns the default type (Variant data type) to your function's result. When you specify the data type for your function's result, you get the same advantages as when you specify the data type for your variables; your procedure uses memory more efficiently, and therefore it runs faster.

Let's take a look at an example of a function that returns an integer number, although the arguments passed to it are declared as Single data types in a calling subroutine.

1. Add a new module to the MyFunctions (Chap04.xls) project and change the module's name to Sample3.

2. Activate the Sample3 module and enter the HowMuch subroutine, as shown below:

Sub HowMuch()

Dim num1 As Single Dim num2 As Single Dim result As Single num1 = 45.33 num2 = 19.24

result = MultiplyIt(num1, num2) MsgBox result End Sub

3. Enter the following function procedure below the HowMuch subroutine:

Function MultiplyIt(num1,num2) As Integer

MultiplyIt = num1 * num2 End Function

Because the values stored in the variables num1 and num2 are not whole numbers, to ensure that the result of multiplication is a whole number, you may want to assign the Integer data type to the result of the function. If you don't assign the data type to the MultiplyIt function's result, the HowMuch procedure will display the result in the data type specified in the declaration line of the result variable. Instead of 872, the result of the multiplication will be 872.1492.

To make the MultiplyIt function more useful, you can pass different values each time you run the procedure by using the InputBox function, instead of hard coding the values to be used in the multiplication. Take a few minutes to modify the HowMuch procedure on your own, following the example of the EnterText subroutine that was created in the preceding section.

0 0

Post a comment