Access VBA Macro Programming

(Joao Candeias) #1

the declarations section of the code module. If you look at a module within the VB Editor
window, you will see a heading called (General) in the top left of the module window and a
heading called (Declarations) in the top right of the module window. Click (Declarations), and
you will go straight to the declarations section. Do not worry if it appears you are not typing
into a defined section. Type the following statement. As soon as you type a declaration, a line
will automatically appear underneath to show it is within the declarations section.


Option Explicit


This prevents implicit declarations from being used. Now you have to defineTempVal:


Dim TempVal


If you refer totemvalduring execution, an error message will be displayed, stating that the
variable has not been defined.


NOTE
Option Explicit works on a per-module basis—it must be placed in the declarations section of every code
module you want it to apply to unless you define the variable as a global variable. A global variable is valid
right across your project and can be used by the code in any module. See the section later in this chapter
called “Global Variables.”

Which method you use (implicit or explicit) depends on your personal preference. Coding
is often much faster using implicit because you do not have to initially define your variables
before you use them. You can simply make variable statements, and VBA will take care of
the rest. However, as discussed, this can lead to errors unless you have a good memory for
variables you are using and have the experience to know exactly what you are doing. Implicit
can also make it more difficult for someone else to understand your code. Using Option
Explicit is the best practice and helps stop runtime errors.


The Scope and Lifetime of Variables


If you declare a variable within a procedure, only code within that procedure can access that
variable. The scope is local to that procedure. You will often need variables that can be used
by several procedures or even the whole application. For these reasons, you can declare a
variable at the local, module, or global level.


Local Variables


Alocalvariable usesDim,Static, orReDim(arrays only) to declare the variable within a
procedure. Several procedures can have a variable calledtemp, but because every variable is
local to its procedure, they all act independently of each other and can hold different values.
Local variables declared with theDimstatement remain in existence only as long as the


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

Free download pdf