Databases Reference
In-Depth Information
Appendix F: XL: Scope of Variables
in Visual Basic
for Applications
This article was previously published under Q141693
Article ID: 141693
Last Review : August 17, 2005
Revision: 2.3
F. 1
SUMMARY
The scope of a variable is determined at the time the variable is declared. In Microsoft Visual
Basic for Applications, the three scopes available for variables are procedure, module, and public.
The “More Information” section of this article describes each scope in detail.
F. 2
MORE INFORMATION
F.2.1 P
(L
) S
ROCEDURE
OCAL
COPE
A local variable with procedure scope is recognized only within the procedure in which it is
declared. A local variable can be declared with a Dim or Static statement.
Dim:
When a local variable is declared with the Dim statement, the variable remains in existence only as
long as the procedure in which it is declared is running. Usually, when the procedure is finished running,
the values of the procedure's local variables are not preserved, and the memory allocated to those
variables is released. The next time the procedure is executed, all of its local variables are reinitialized.
For example, in the following sample macros, “Example1” and “Example2,” the variable X is
declared in each of the modules. Each variable X is independent of the other — the variable is
only recognized within its respective procedure.
Sub Example1()
Dim X As Integer
' Local variable, not the same as X in Example2.
X = 100
MsgBox "The value of X is " & X
End Sub
Sub Example2()
Dim X As String
' Local variable, not the same as X in Example1.
415
Search WWH ::




Custom Search