By "subroutine" we mean a Sub procedure that is "called" by another VBA program. In writing a VBA procedure, it may be necessary to repeat the same instructions several times within the procedure. Instead of repeating the same lines of code over and over in your procedure, you can place this code in a separate Sub program; this subroutine or subprogram is then executed by the main program each time it is required.

There are several ways to execute a subroutine within a main program. The two most common are by using the Call command, or by using the name of the subroutine. These are illustrated in Figure 2-11. MainProgram calls subroutines Taskl and Task2, each of which requires arguments that are passed from the main program to the subroutine and/or are returned from the subroutine to the main program.

Sub MainProgram()


Call Taskl (argument1,argument2) etc

Task2 argument3,argument4

etc End Sub

Sub Taskl (ArgName1,ArgName2)

etc End Sub

Sub Task2(ArgName3,ArgName4) etc

End Sub_

Figure 2-11. A main program illustrating the different syntax of subroutine calls.

The two methods use different syntax if the subroutine requires arguments. If the Call command is used, the arguments must be enclosed in parentheses. If only the subroutine name is used, the parentheses must be omitted. Note that the variable names of the arguments in the calling statement and in the subroutine do not have to be the same.

There are several advantages to using subroutines: you eliminate the repetition of code, and you make the programming clearer by adopting a modular approach. Perhaps most important, a subroutine that is of general usefulness can be called by several different procedures.

0 0

Post a comment