Learn Access 2003 VBA with The Smart Method
286
www.LearnAccessVBA.com
7: Constants
7-1
Name constants using upper case and underscores.
Programmers should always be aware of which variables are constants. Clearly identify them by
always using the upper-case/underscore style for constant names (and only for constant names). It
will then always be easy to differentiate between variables and constants in your code.
Good:
TSM_APPLICATION_STATUS
Bad:
conApplicationStatus
You’ll often see code written using the “bad" convention above. Note that Microsoft do not observe
this rule with their own constants such as vbRed.
7-2
Constants should always be named with a prefix that is unlikely to be used by any other third
party code.
Microsoft use the prefix vb for all of their constants. You should use at least three letters, perhaps
your own initials or the name of the application you are writing. As there are 27
3
combinations of
three-letter prefixes it is unlikely (though not impossible) that your constant prefixes will coincide
with those used by a third party library.
8: Variable declaration
8-1
The Require Variable Declaration option must always be switched on.
This can be done by selecting Tools Options from the code editor window. The Option Explicit
command will then be included at the top of every new (but not existing) module.
8-2
All variables must be strongly typed.
This includes variables declared as parameters for subs and functions.
Good:
Dim strFirstName as string
Sub DeleteCustomer( lngCustomerID as Long)
Bad:
Dim strFirstName
Sub DeleteCustomer( lngCustomerID)
8-3
All variables must be declared and typed with a dedicated Dim statement.
It is possible to declare more than one variable within a single Dim statement but this practice can
cause problems.
At first glance you may think that:
Dim strOne,strTwo as string
Was functionally equivalent to:
Dim strOne as String
Dim strTwo as String
The first example would, in fact, declare strOne as a Variant and only strTwo as a string.
Good:
Dim strFirstName as string
Dim strLastName as string
Bad:
Dim strFirstName, strLastName as string
'
first variable is a variant