A subroutine can call other subroutines or functions. The following is the general form of a subroutine that calls another subroutine and a function. Again the subroutine name follows the same rules as for variables.
Note: A function or subroutine can have many arguments or no arguments.
Note: A subroutine must have an argument for each variable input or variable output that is needed. For example a subroutine with Arg6 = Arg4 + Arg5, requires three arguments.
Sub main()
instructions
variable = myFunction(a,b)
Call mysub(d,e,f)
myVar = f
End Sub
Function myFunction(Arg1,Arg2)
instructions
myFunction = Arg1 + Arg2
End Function
Sub mysub(Arg4,Arg5,Arg6)
instructions
Arg6 = Arg4 + Arg5
End Sub
Sub Test14() uses a function to add three numbers, and a subroutine to multiply three numbers. Test14() prints c = 7 and d = 10.
' Example subroutine that calls another subroutine and a function.
Sub Test14()
Dim a As Long 'Declares a, b, c, d as integers
Dim b As Long
Dim c As Long
Dim d As Long
a = 1 'Sets a equal to 1
b = 2 'Sets b equal to 2
c = funcAdd(a, b) 'Sets c equal to funcAdd(a,b), with a and b being
MsgBox "c = " & c 'substituted for Arg1 and Arg2.
Call subMultiply(a, b, d) 'Calls sub subMultiply(a,b,d) with a, b, d being
MsgBox "d = " & d 'substituted for Arg3, Arg4, and Arg5.
End Sub
'Function for Test14()
Function funcAdd(Arg1, Arg2) As Long 'Function declared as Long.
Dim intVariable As Long 'intVariable is locally defined to the function
intVariable = 4
funcAdd = Arg1 + Arg2 + intVariable 'funcAdd is equal to 7
End Function
'Sub for Test14()
Sub subMultiply(Arg3, Arg4, Arg5)
Dim intResult As Long 'intResult is locally defined to the subroutine
intResult = 2 + 3
Arg5 = Arg3 * Arg4 * intResult 'd = Arg5 is equal to 10
End Sub
Sub Test14() calls a function and a subroutine. These are the basic building blocks of all programs. Read all the comments. The function funcAdd(Arg1, Arg2) has Arg1 and Arg2 substituted with the values a and b. subMultiply() has the values a, b, d substituted into Arg3, Arg4, Arg5. After the calculations in subMultiply() the values of Arg3, Arg4, Arg5 are passed by reference back to a, b, d.
Notice that intVariable and intResult in the procedures must be declared or you will get the error message Variable not defined. Do not declare Arg1, Arg2 in the function, and do not declare Arg3, Arg4, Arg5 in the subroutine or you will get the error message Duplicate declaration in current scope.
Notice if you copied all the subroutines, and functions above to the same Code Window, you may have two functions or subroutines with the same name. You must delete one of them. If you don’t, you will get the following pop up box.
Table of Contents
Ch1-Introduction
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Subs & Functions
Ch6-Read & Write
Ch7-Operators
Ch8-Built-in Functions
Ch9-Built-in Examples
Ch10-Debugging
Ch11-Running Subs
Ch12-Sample Programs
Ch13-WS Formulas
Ch14-Questions