Microsoft Office Tutorials and References
In Depth Information
Passing Arguments to Procedures
A procedure’s arguments can mix and match by value and by reference. Arguments preceded
with ByVal are passed by value; all others are passed by reference.
If you pass a variable defined as a user-defined data type to a procedure, it must be
passed by reference. Attempting to pass it by value generates an error.
Because I didn’t declare a data type for any of the arguments in the preceding examples, all the
arguments have been of the Variant data type. But a procedure that uses arguments can
define the data types directly in the argument list. The following is a Sub statement for a
procedure with two arguments of different data types. The first is declared as an integer, and the
second is declared as a string.
Sub Process(Iterations As Integer, TheFile As String)
Using public variables versus passing
arguments to a procedure
In Chapter 8, I point out how a variable declared as Public (at the top of the module) is
available to all procedures in the module. In some cases, you may want to access a Public variable
rather than pass the variable as an argument when calling another procedure.
For example, the procedure that follows passes the value of MonthVal to the ProcessMonth
procedure:
Sub MySub()
Dim MonthVal as Integer
‘ ... [code goes here]
MonthVal = 4
Call ProcessMonth(MonthVal)
‘ ... [code goes here]
End Sub
An alternative approach, which doesn’t use an argument, is
Public MonthVal as Integer
Sub MySub()
‘ ... [code goes here]
MonthVal = 4
Call ProcessMonth2
‘ ... [code goes here]
End Sub
In the revised code, because MonthVal is a public variable, the ProcessMonth2 procedure
can access it, thus eliminating the need for an argument for the ProcessMonth2 procedure.
 
Search JabSto ::




Custom Search