Page 75 - Excel Progamming Weekend Crash Course
P. 75
d540629 ch04.qxd 9/2/03 9:28 AM Page 50
50 Friday Evening
VBA Naming Rules
VBA’s naming rules apply to symbolic constants, variables, properties, and just
about anything else you can assign a name to in code. A VBA name:
Must start with a letter
Can be up to 255 characters in length
Cannot be a VBA keyword
Cannot contain a period, space, or the characters: !, @, #, &, %, or $
It’s a good idea to create descriptive names that provide some idea of what the
variable or other named element does. Because you cannot use spaces, multi-
word names can be made clearer using a combination of upper- and lowercase
(for example, InterestRate) or by using the underscore in place of spaces (for
example, Total_2001). Case does not matter; thus, Total, total, and TOTAL are
considered the same name in VBA.
I have found it useful to use all uppercase for constant names, and a combi-
nation of upper- and lowercase for other elements such as variables. For
Tip example, INTEREST_RATE would be a constant while InterestRate would be a
variable. This is certainly not required by VBA, but it does make it easy to
distinguish constants from variables in code.
Declaring and Using Variables
As the name suggests, a variable holds data that can change during program execution. In
VBA, a variable has a type that determines what kind of data the variable can hold. When
you create or declare a variable, you specify its type according to the needs of the program.
In its simplest form, the syntax for declaring a variable is a single statement containing:
1. The Dim keyword.
2. The variable name.
3. The As keyword.
4. The name of the variable type.
Thus the code would look like:
Dim varname As type
You can also declare two or more variables on the same line as follows:
Dim varname1 As type1, varname2 As type2, ...
Variable names follow the same naming rules that were presented earlier in this session.
A variable name must be unique within its scope. You learn about scope later in the session.