Chapter 9
Working with Arrays
and Collections
In This Chapter
Using arrays within a program
Using collections within a program
Creating new data types
Defining collections within a program
T
o
this point in the book, all the data types you’ve used have one thing in
common — they store a single data element. When you create an integer,
it holds a single number. Placing a new number within the integer removes
the old value. However, the real world doesn’t work this way. A computer can
have more than one disk drive. Your contact database contains more than
one name. A mailbox can contain more than one piece of mail. You need a
method of storing more than one piece of information
in a single variable so
that you can model the real world in your programs. VBA provides two meth-
ods of doing this: arrays and collections.
Arrays
provide a way for your programs to store more than one item in a
single container. Think of the array as a large box with a bunch of small boxes
inside. Each small box can store a single value. You decide how many small
boxes the array can hold when you create the array. Use arrays when you
need to store a number of related items of the same data type.
Collections
always relate to a group or series of
objects that are combined in
a single container. In most cases, a main object contains one or more sub-
objects. For example, an Excel
Application
object contains a
Workbooks
collection, and a
Workbook
object contains a
Sheets
collection. The
Application
can contain one or more
Workbooks
,
and an individual
Workbook
can contain one or more
Sheets
. A Word
Section
object can
contain a
HeadersFooters
collection. Microsoft Office and many third-party
products are packed with object collections that you can access from VBA.
15_046500 ch09.qxp 12/5/06 5:36 PM Page 205
In this chapter, I also demonstrate how you can create your own data types.
A
data type
is a way to mark information so that you can understand it better.
The computer doesn’t care about data types. VBA uses data types to enforce
certain
data behaviors, but it doesn’t really understand them. The use of a
data type is for your benefit so that you can understand the information
better.
Using Arrays for Structured Storage
An
array
is a list of items. When you write a list of tasks to perform for the
day, you create an array. The piece of paper is a single container that holds a
number
of strings, each of which is a task that you have to perform. Likewise,
you can create a single piece of paper in your VBA program — an array —
and use that array to hold multiple items.
Understanding array usage
You can define arrays by using several techniques. However, all these tech-
niques use the same basic approach. Listing 9-1 contains an example that
demonstrates the essential array usage process. (You can find the source
code for this example on the Dummies.com
site at
http://www.dummies.
com/go/vbafd5e
.)
Do'stlaringiz bilan baham: