Calling Functions and Sub Procedures

When you develop an application, you should not attempt to place all your code in one large procedure. You should write small procedures that carry out specific tasks, and test each procedure independently. You can then write a master procedure that runs your task procedures. This approach makes the testing and debugging of the application much simpler, and also makes it easier to modify the application later.

The following code illustrates this modular approach, although in a practical application your procedures would have many more lines of code:

Sub Master()

SalesData = GetInput("Enter Sales Data") If SalesData = False Then Exit Sub PostInput SalesData, "B3" End Sub

Function GetInput(Message) Data = InputBox(Message)

If Data = "" Then GetInput = False Else GetInput = Data End Function

Sub PostInput(InputData, Target)

Range(Target).Value = InputData End Sub

Master uses the Getlnput function and the Postlnput sub procedure. Getlnput has one input parameter, which passes the prompt message for the inputBox function and tests for a zero-length string in the response. A value of False is returned if this is found. Otherwise, Getlnput returns the response.

Master tests the return value from Getlnput and exits if it is False. Otherwise, Master calls Postlnput, passing two values that define the data to be posted and the cell the data is to be posted to.

Note that sub procedures can accept input parameters, just like function procedures, if they are called from another procedure. You can't run a sub procedure with input parameters directly.

Also note that, when calling Postlnput and passing two parameters to it, Master does not place parentheses around the parameters. Because sub procedures do not generate a return value, you should not put parentheses around the arguments when one is called, except when using the Call statement that is discussed next.

When calling your own functions and subs, you can specify parameters by name, just as you can with built-in procedures. The following version of Master uses this technique:

Sub Master()

SalesData = GetInput(Message:="Enter Sales Data") If SalesData = False Then Exit Sub

Postlnput Target:="B3", InputData:=SalesData

End Sub

The Call Statement

When running a sub procedure from another procedure, you can use the Call statement. There is no particular benefit in doing this; it is just an alternative to the previous method. Master can be modified as follows:

Sub Master()

SalesData = GetInput("Enter Sales Data") If SalesData = False Then Exit Sub

Call PostInput(SalesData, "B3")

End Sub

Note that if you use Call, you must put parentheses around the parameters passed to the called procedure, regardless of the fact that there is no return value from the procedure. You can also use Call with a function, but only if the return value is not used.

0 0

Post a comment