Microsoft Office Tutorials and References
In Depth Information
Figure 5-3. Dialog that appears if the static NotFirstTime is false
Static NotFirstTime As Boolean
' If first time, then ask for permission
If NotFirstTime = False Then
If MsgBox("Comic Sans is a bit informal. Proceed?", _
vbYesNo) = vbYes Then
' Make the change
Selection.Font.Name = "Comic Sans MS"
End If
' No longer the first time
NotFirstTime = True
' If not the first time, just make the change
Selection.Font.Name = "Comic Sans MS"
End If
End Sub
The If statement checks to see if the value of NotFirstTime is False, as it will be the first time
the procedure is called. In this case, a message box is displayed, as shown in Figure 5-3 . If the
user chooses the Yes button, the font is changed. In either case, the static Boolean variable
NotFirstTime is set to True. Precisely because NotFirstTime is static, this value will be
retained even after the macro ends (but not if the document is closed).
Figure 5-3. Dialog that appears if the static NotFirstTime is false
The next time the macro is executed, the variable NotFirstTime will be True , and so the If
If NotFirstTime = False Then
will be False and the MsgBox function will not be executed. Instead, the Else code will execute.
This code just changes the font, without bothering the user with a message box.
Static variables are not used very often, but they can be quite useful at times.
It may have occurred to you that we could accomplish the same effect by using a module-level
private variable to keep a record of whether or not the macro has been called, instead of a static
local variable. However, it is considered better programming style to use the most restrictive scope
possible which, in this case, is a local variable with an "extended" lifetime. This helps prevent
accidental alteration of the variable in other portions of the code. (Remember that this code may
be part of a much larger code module, with a lot of things going on. It is better to hide the
NotFirstTime variable from this other code.)
5.4.13 Variable Initialization
When a procedure begins execution, all of its local variables are automatically initialized , that is,
given initial values. In general, however, it is not good programming practice to rely on this
Search JabSto ::

Custom Search