Passing an Argument to a Procedure

When you call the Power procedure, for example, in the Click event of the form Power(5)

the output would be: 5 to the 2nd power = 25

The statement Power(5) has the effect of assigning the value 5 to the argument num in Power. Thus, the statement in Power

Debug.Write(num & " to the 2nd power = " & num a 2)

executes as follows when the value passed is 5: Debug.Write(5 & " to the 2nd power = " & 5 a 2)

When you call a procedure, you must pass the exact number of arguments specified in the procedure's declaration. For example, if you tried to call the Power procedure with no arguments

Power()

the compiler would complain: "Argument not specified for the parameter 'num' of 'Private Sub Power(num As Integer)'."

Similarly, if you tried to call the Power procedure with more than one argument Power(5, 3)

the compiler would complain: "Too many arguments to 'Private Sub Power(num As Integer)'."

The argument passed also must be the same data type specified in the procedure's declaration or converted to that data type with a widening conversion. For example, if you tried to call the Power subroutine as follows

Dim strInput As String strInput = InputBox("Enter a number")

Power(strInput)

the compiler would complain: "Option Strict On disallows implicit conversions from 'String' to 'Integer'."

Tip You could solve that problem by using the type conversion keyword

CInt in the last line: Power(CInt(strInput)).

Was this article helpful?

0 0

Post a comment