Databases Reference
In-Depth Information
Dim Age As Integer, Name As String, Money As Currency
declares three variables. Note, however, that a declaration such as:
Dim Age, Height, Weight As Integer
is legal, but Age and Height are declared as Variants, not Integers. In other words, we
must specify the type for each variable explicitly.
It is also possible to tell VBA the type of the variable by appending a special character to
the variable name. In particular, VBA allows the type-declaration suffixes shown in
Table 10-2. (I personally dislike these suffixes, but they do save space.)
Table 10-2. T ype-declaration suffixes
Suffix
Type
%
i nteger
&
long
!
s ingle
#
double
@
c urrency
$
string
For instance, the line:
Dim Name$
declares a variable called Name$ of type String. We can then write:
Name$ = "Donna"
Finally, let us note that although Access allows variable and constant declarations to be
placed anywhere within a procedure (before the item is used, that is), it is generally good
programming practice to place all such declarations at the beginning of the procedure.
This improves code readability and makes housekeeping much simpler.
10.4.2 The Importance of Explicit Variable Declaration
I have said that using the Variant data type generally wastes memory and often results in
poorer performance, and that all variables are assumed to be variants unless you specify
otherwise. There is an additional, even more important reason to declare all variables
explicitly. This has to do with making typing errors, which we all do from time to time.
In particular, if we accidentally misspell a variable name, VBA will think we mean to
create a new variable!
Search WWH ::




Custom Search