MS-Access / Getting Started

Module-Level Variables

A module-level variable is declared for a particular module. It is available to all procedures within that module but not to the rest of the application. Module-level variables remain in existence for the lifetime of the application and preserve their values.

Dim TempVal

This would be placed in the declarations section of the module instead of an actual procedure on that module.

Global Variables

Global variables are declared in the declarations part of a module with the Global statement, but they can be accessed by any code within the application. Global variables exist and retain their values for the lifetime of the application.

Global TempVal

Again, this would be placed in the declarations section of any module. Because you have specified that it is global, it can be accessed for any part of your code.

Name Conflicts and Shadowing

A variable cannot change scope while your code is running. However, you can have a variable with the same name in a different scope or module. You can have a global variable called temp and also a local variable in a procedure called temp. References to temp within the procedure would access the local variable temp, and references outside the procedure would access the global variable temp. In this case, the local variable shadows (that is, is accessed in preference to) less local variables. The only way to use the global variable over the local variable is to give it a different name. Shadowing can be confusing and can produce subtle errors that are difficult to debug. The best way is to use unique names for all variables. The names of module-level and global variables can also cause conflicts with procedure names. A procedure (a subroutine) has global scope unless it is declared privately. A global variable cannot have the same name as any public procedure in any code module.

Static Variables

Variables also have a lifetime based on their scope. Module and global variables are preserved for the lifetime of the application, which means they hold their values while the application is executing until the user closes the application. Local variables declared with Dim exist only when the procedure is executing. When it stops, the values are not preserved and the memory is released. The next execution reinitializes the variables for the lifetime of the procedure. You should only use local variables to hold values that are being used during that procedure. If you expect to access them from other modules, they need to be global. However, you can use the Static keyword to declare and preserve a local variable:

Static Temp

You can make all local variables static by placing the Static keyword at the beginning of a procedure heading:

Static Sub Test_MyProc()
[Previous] [Contents] [Next]