Microsoft Office Tutorials and References
In Depth Information
Chapter 3: Writing Smarter Code
code is running. The data in an array is defined in code, not in a table, so
getting to the data stored in the array isn’t easy.
The syntax for declaring an array is almost identical to that for creating a
variable, but you need to define the number of dimensions in the array and
the number of elements in each dimension of the array. An array can have up
to 60 dimensions and virtually any number of elements within each dimension.
The basic syntax for declaring an array with the Dim statement is
Dim varname [([ subscripts ])] [As type ] [,varname[([subscripts])] [As type]] . .
In this statement,
varname is the name assigned each element in the array.
subscripts is the number of elements in each dimension, with the
dimensions separated by commas. It can contain the optional keyword
To to specify the starting and ending subscripts.
type is any valid VBA data type.
All arrays are zero-based unless you specify otherwise, which means that
the first item in the array has a subscript of 0 (zero) rather than 1. The
number of elements specified is actually one less than the total number of
elements that the array contains.
The following Dim statement declares a one-dimensional array named
Colors that contains four string elements (numbered 0, 1, 2, and 3):
Dim Colors(3) as String
The following lines of code show how you can then assign a value to each
element in the array. Because the first item always has a subscript of 0, you
actually place four items in the array rather than three:
Colors(0) = “black”
Colors(1) = “red”
Colors(2) = “blue”
Colors(3) = “green”
Having the first element in an array start with 0 can be counterintuitive for us
humans, because we tend to think of the first item in a list as being number
1. You can force the first element to be 1 by specifying a range (rather than
a number) of elements in the Dim statement. The following Dim statement
declares an array of three elements, with subscripts ranging from 1 to 3. The
lines after the Dim statement assign values to each of those elements:
Dim Colors(1 To 3) as String
Colors(1) = “red”
Colors(2) = “blue”
Colors(3) = “green”
Search JabSto ::

Custom Search