Access VBA Macro Programming

(Joao Candeias) #1

Global Variables


Globalvariables are declared in the declarations part of a module with theGlobalstatement,
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
calledtempand also a local variable in a procedure calledtemp. References totempwithin
the procedure would access the local variabletemp, and references outside the procedure
would access the global variabletemp. In this case, the local variableshadows(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, as you will
see in Chapter 3. 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
Dimexist 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 theStatickeyword to declare and preserve a local variable:


Static Temp


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


Static Sub Test_MyProc()


Chapter 2: Variables, Arrays, Constants, and Data Types 17

Free download pdf