Microsoft Office Tutorials and References
In Depth Information
Example 5-2. ToComic() Modified to Use a Static Variable
destroyed and its value is lost. It is the lifetime that determines the existence of a variable; its
scope determines its visibility.
Thus, consider the following procedures:
Sub ProcedureA()
Call ProcedureB
Call ProcedureB
Call ProcedureB
Call ProcedureB
Call ProcedureB
End Sub
Sub ProcedureB()
Dim x As Integer
x = 5
. . .
End Sub
When ProcedureA is executed, it simply calls ProcedureB five times. Each time
ProcedureB is called, the local variable x is created anew and destroyed at the end of that call.
Thus, x is created and destroyed five times.
Normally, this is just want we want. However, there are times when we would like the lifetime of
a local variable to persist longer than the lifetime of the procedure in which it is declared. As an
example, we may want a procedure to do something special the first time it is called, but not
subsequent times. For instance, the following one-line macro changes the font of the selected cells
to Comic Sans:
Sub ToComic()
Selection.Font.Name = "Comic Sans"
End Sub
Suppose, however, that we wish to warn the user that Comic Sans is a bit informal and ask if he or
she really wants to make this change. We don't want to make a pest of ourselves by asking every
time the user invokes this macro. What we need is a local variable with a "memory" that will
allow it to keep track of whether or not a particular call to ToComic is the first call or not. This is
done with a static variable.
A static variable is a local variable whose lifetime is the lifetime of the entire module, not just the
procedure in which it was declared. In fact, a static variable retains its value as long as the
document or template containing the code module is active (even if no code is running).
Thus, a static variable has the scope of a local variable, but the lifetime of a module-level variable.
C'est tout dire !
Consider now the modification of the preceding macro, which is shown in Example 5-2 . The code
first declares a static Boolean variable called NotFirstTime . It may seem simpler to use a
variable called FirstTime , but there is a problem. Namely, Boolean variables are automatically
initialized as False, so the first time that the ToComic macro is run, FirstTime would be False,
which is not want we want. (We will discuss variable initialization a bit later.)
Example 5-2. ToComic() Modified to Use a Static Variable
Sub ToComic()
' Declare static Boolean variable
Search JabSto ::

Custom Search