Access VBA Macro Programming

(Joao Candeias) #1
almost like a spreadsheet. A spreadsheet has many cells that can hold information, and an
array can be set up to have many cells or locations in exactly the same way.
A variable can have its value changed by the program when running, which is why it is
called a variable. The same rules apply from the filing cabinet example, in that you do not
mix the data types between the variables. If a variable has been defined as a certain type, it
will not accept data specified as another type. For example, if you have defined a variable as
an integer (whole) number, you cannot put text into it, or if you put a floating point number
(with decimal places) into an integer, you will lose the decimal places.
As your program runs, you often need a place to store data temporarily. Use variables to
store values while your code is executing. Within a procedure, you declare a variable using
theDimstatement, supplying a name for the variable:
Dimvariablename [As type]
Variable names must follow these rules:

 They must begin with a letter.
 They must contain only letters, numbers, or the underscore character—no spaces!
 They must not exceed 40 characters.
 They must not be a reserved word (see the section “Reserved Words” at the end of this
chapter).

The optionalAstype clause allows you to define the data type of the variable you are
declaring. If you omit the type, it defaults to the Variant data type discussed in the next section.

Dim MyInteger as Integer

Implicit Declaration


You do not have to declare a variable before using it. You can just include the statement

TempVal=6

A variable will automatically be created forTempValas a variant (default type), and it will
have the value of 6.
However, a problem with doing this is that it can lead to subtle errors in your code if you
misspell the name of the variable in a later statement. For example, if you refer to it astemval
instead oftempval, you know what you mean but VBA does not. It assumes thattemvalis a
new variable and assigns it as such. The old variable,tempval, is still there but is no longer
being used. You now have two different variables, although you think you only have one. This
can lead to enormous problems that can take some time to straighten out in your code.

Explicit Declaration


To avoid the problem of misnaming variables, you can stipulate that VBA always generate an
error message whenever it encounters a variable not declared. To do this, you’ll need to go to

14 Microsoft Access 2010 VBA Macro Programming

Free download pdf