Microsoft Office Tutorials and References
In Depth Information
Understanding a Variable’s Scope
figurE 6-4
undErsTAnding A VAriABlE’s scopE
Variables and constants (explained in the next section) do not live forever in memory. They have
a set lifetime and visibility within macros and modules. A variable’s lifetime begins when it is
declared, and ends when the macro that declared the variable completes its execution.
local Macro level only
The visibility of a variable or constant also depends on how it is declared. If declared within a
macro, a variable can only be used by that macro. For example:
Sub Macro1()
Dim intAdd As Integer, intSum As Integer
intAdd = 31
intSum = intAdd + 10
MsgBox intSum
End Sub
Module level
It is possible for a variable to be visible and usable in more than one macro by having the declaration
statement at the top of the module instead of inside a particular macro. In Figure 6-5, both Macro1
and Macro2 can utilize the intSum and intAdd variables.
 
Search JabSto ::




Custom Search