Microsoft Office Tutorials and References
In Depth Information
Chapter 3: Writing Smarter Code
Defining constants
A constant is similar to a variable, in that it has a name, a data type, and a
value. Unlike a variable (whose contents can change at any time), a constant
has a fixed value. Constants are often used to assign a short name to some
value that must be used repeatedly throughout the code but never changed.
To declare a constant, you use the Const keyword. The simplified syntax for
the Const keyword is
Const name [As type value [, name [As type value ]... ]=
You define the name, data type ( type ), and value of the constant on a single
line. The rules for coming up with a name are the same as those for a variable:
It must start with a letter, can’t contain blank spaces or punctuation, and
can’t be the same as a VBA keyword.
As an example of creating a constant, the following statement defines a
constant named pi as a double-precision number containing the value
Const pi As Double = 3.141592654
You can declare multiple constants in a single Const statement by separating
them with commas. The following example statement declares two constants:
a number named x of the Byte data type, with a value of 10, and a string
named myName, containing the text “Billy”:
Const x As Byte = 10, myName As String = “Billy”
Constants tend to be private to the modules in which they’re defined. If you
want to ensure that a constant is available to all objects and all modules
within the database, precede Const with the Public keyword, as follows:
Public Const pi As Double = 3.141592654
Chapter 3
Organizing variables into arrays
An array is a collection of variables organized into a list or table. Each
item’s name is the same, but each array has one or more subscripts that
uniquely identify each item in the array based on its position in the array.
The subscript is one or more numbers, enclosed in parentheses, that follow
the name. If Colors is the name of an array, for example, Colors(0)
(pronounced colors sub zero) is the first item in the list, Colors(1) is the
second item in the list, and so on.
In a sense, an array is like a database table in that the data can be organized
into rows and columns. Also, you can use VBA to manipulate data stored in
tables. The only time you really want to use an array is when you work with
a small amount of data that either never changes or changes only while the
Search JabSto ::

Custom Search