Variable Scope

Variables and constants have a scope, which indicates where in the program the variable or constant is recognized (or visible to the code). The scope of a variable or constant can be either procedure-level (also called local), module-level private, or module-level public. The rules may seem a bit involved at first, but they do make sense. Procedure-level (local) variables

A local or procedure-level variable or constant is a variable or constant that is declared within a procedure, as is the case with the variable LocalVar and the constant LocalConstant in Figure 5-2. A local variable or constant is not visible outside of the procedure. Thus, for instance, if we try to run ProcedureB in Figure 5-2, we will get the error message, "Variable not defined," and the name LocalVar will be highlighted.

Figure 5-2. Examples of variable scope

One of the advantages of local variables is that we can use the same name in different procedures without conflict, since each variable is visible only to its own procedure. Module-level variables

A module-level variable (or constant) is one that is declared in the declarations section of a code module (standard, class, or UserForm). Module-level variables and constants come in two flavors: private and public.

Simply put, a module-level public variable (or constant) is available to all procedures in all of the modules in the project, not just the module in which it is declared, whereas a module-level private variable (or constant) is available only to the procedures in the module in which it was declared.

Public variables and constants are declared using the Public keyword, as in:

Public APubInt As Integer Public Const APubConst = 7

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.

0 0


  • Wanda
    What is class llevel scope in vba?
    7 years ago

Post a comment