A collection is an ordered set of items that
you can refer to as a unit. VB6 makes use of collections in many
ways, such as keeping track of controls on a form and system
printers. VB6 also provides a generic Collection object for you to
use in your programs. What makes the Collection object so useful is
that the items it contains can be essentially anything—variables,
literal numbers or text, objects, and so on. And, they don’t have
to be the same data type.
To create a Collection object, you use the
usual VB syntax:
Dim col As New Collection
Then, you use the Add method to add items to
the collection:
col.Add item, key, before, after
Here’s a description of each of the
arguments:
-
Item is the item being
added. This argument is required. -
Key is an optional string
that identifies the item. Key must be unique within the
collection. -
Before is an optional
number that specifies the position of the new item in the
collection as the index of the existing item before which the new
item is to be placed. -
After is an optional number
that specifies the position of the new item in the collection as
the index of the existing item after which the new item is to be
placed.
You wouldn’t use the before and after arguments at the same
time. If you omit both arguments, the new item is placed at the end
of the collection. If you use one of these arguments, it must refer
to an existing member of the collection or else an error will
occur.
To retrieve an item from a collection, use the
Item method:
col.Item(index)
The index argument is either a
number specifying the position of the item in the collection, or
the key string that was specified when the item was added. If the
index argument doesn’t
match an item in the collection, an error occurs. Note that the
numerical index is one-based; in other words, it runs from 1 to the
number of items in the collection. Since Item is the default
method, you can use the shorthand syntax like this:
col(index)
To delete an item, use the Remove method. Its
syntax is exactly the same as Item. If you remove an item that
isn’t the last item, other items move up to fill in the space of
the deleted item.
The Collection object has one property, Count.
It returns the number of items in the collection.
Collections can be useful in various
situations. For instance, suppose your program lets the user create
one or more child windows. You can use a collection to keep track
of them and then destroy them as needed. First, create the
collection:
Dim col As New Collection
Then, when each window is created, add it to
the collection:
Dim f As New Form2
col.Add f
f.Show
When it’s time to close all the windows, loop
through the collection, like this:
Dim i As Integer
Dim f As Form
For i = 1 To col.Count
Set f = col(i)
f.Visible = False
Set f = Nothing
Next
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!