Scope and Lifetime of Variables and Constants

Variables and constants have a scope and life cycle and scope similar to procedures. With respect to life cycle, the variables within sub and function procedures generally live while the procedure is executing. The Static keyword can be used when necessary to alter this traditional lifetime and preserve the value of the variable after the last procedure that uses it finishes executing.

The scope of a variable determines from where the variable can be seen or used. A variable created locally within a procedure can be seen only by that procedure. A variable that is declared in the General Declarations section can be seen by all procedures in that particular module or by procedures in all modules, depending on whether it is declared as public or private. If the variable is declared with the Public keyword, all procedures in all modules can use and see it. If it is not, the variable is private and only the procedures in the particular module where the declaration is located can see it.

Try It Out Declaring a Public Variable

Next, you can declare a public variable to illustrate how to make variables visible from procedures in any module.

1. In the modBusinessLogic standard module, go to the General Declarations section (Figure 2.26).

(General)

(Declarations)

T

Option Compare Database Option Explicit

F-iblic strTest A3 String

2. Add a public constant called strTest to the General Declarations section, as shown in the previous figure.

0 0

Post a comment