Microsoft Office Tutorials and References
In Depth Information
5.4.12 Variable Lifetime
Private variables and constants are declared using the Private keyword, as in:
Private APrivateInt As Integer
Private Const APrivateConst = 7
The Dim keyword, when used at the module level, has the same scope as Private , but is not as
clear, so it should be avoided.
Public variables are also referred to as global variables , but this descriptive term is not de rigueur .
5.4.12 Variable Lifetime
Variables also have a lifetime. The difference between lifetime and scope is quite simple: lifetime
refers to how long (or when) the variable is valid (that is, retains a value) whereas scope refers to
where the variable is accessible or visible.
To illustrate the difference, consider the following procedure:
Sub ProcedureA()
Dim LocalVar As Integer
LocalVar = 0
Call ProcedureB
LocalVar = 1
End Sub
Note that LocalVar is a local variable. When the line:
Call ProcedureB
is executed, execution switches to ProcedureB . While the lines of ProcedureB are being
executed, the variable LocalVar is out of scope, since it is local to ProcedureA . But it is still
valid. In other words, the variable still exists and has a value, but it is simply not accessible to the
code in ProcedureB . In fact, ProcedureB could also have a local variable named LocalVar ,
which would have nothing to do with the variable of the same name in ProcedureA .
Once ProcedureB has completed, execution continues in ProcedureA with the line:
LocalVar = 1
This is a valid instruction, since the variable LocalVar is back in scope.
Thus, the lifetime of the local variable LocalVar extends from the moment that ProcedureA is
entered to the moment that it is terminated, including the period during which ProcedureB is
being executed as a result of the call to this procedure, even though during that period, LocalVar
is out of scope.
Incidentally, you may notice that the Microsoft help files occasionally get the notions of scope and
visibility mixed up a bit. The creators of the files seem to understand the difference, but they don't
always use the terms correctly.
5.4.12.1 Static variables
To repeat, a variable may go in and out of scope and yet remain valid during that time—that is,
retain a value during that time. However, once the lifetime of a variable expires, the variable is
Search JabSto ::




Custom Search