Microsoft Office Tutorials and References
In Depth Information
Chapter 3: Writing Smarter Code
The following sample Dim statement declares two variables: a string named
ReportName and a long integer named Qty. Then the lines after the Dim
statement assign a value to each variable, using the standard variable
Name = value syntax:
Dim ReportName As String, Qty As Long
ReportName = “Sales Summary Report”
Qty = 50
Understanding the scope and lifetime of variables
Every variable and constant has a scope and a lifetime.
The scope of a variable defines the procedures to which the variable is visible.
You determine the scope of a variable when you declare the variable.
Variables declared at the beginning of a module (before the first procedure
in the module) can be private (visible only to procedures within the same
module) or public (visible to all procedures in all modules). These variables
have module-level scope.
If you use the Public keyword (rather than Dim) to declare a variable at
the module level, the variable is visible to all procedures in all modules. On
the other hand, if you use a Dim or Private statement to define a variable
at the module level, the variable is private to the module. All procedures
defined within the same module can see the variable, but the variable is
invisible to procedures defined in other modules.
When you define a variable within a procedure, that variable has
procedurelevel scope, meaning that the variable is private (visible only) to the
procedure in which it is defined. Only the procedure in which the variable is
defined can see, and use, the variable.
Figure 3-1 shows a module containing several variables declared with Dim,
Private, and Public keywords. Comments in the code describe the scope
of the variables declared within the module, as follows: