Professional Documents
Culture Documents
Programming Visual Basic 6.0 Applications Level 2
Programming Visual Basic 6.0 Applications Level 2
Programming Visual Basic 6.0 Applications Level 2
Level 2
Table of Contents
INDEX......................................................................................................INDEX-1
Working with
Collections
Objectives
• Introduce how collections work.
• See how to use the VBA Collection object.
• Create a collection containing user-defined TextFile objects.
Collection Overview
Before you learn how to create your own collections, let’s start with a quick
overview of the concepts involved.
What Is a Collection?
A collection is an organized group of similar objects. You can think of a
collection as a container into which you can place objects for later retrieval.
Collections are essential to object-based applications because rarely do you
find a complex application with only one object of any given type. Collections
let you store and manage multiple object instances very easily.
A collection is also an object. This means it has its own properties and
methods. You use these properties and methods to manipulate the objects
contained in the collection.
Key Term
Using a Collection
You’ve already used several different collections, perhaps without knowing it.
Visual Basic provides a collection of opened forms, aptly named “Forms.”
Every form provides a collection of controls on that form, again
serendipitously named “Controls.” If you’ve worked with ADO, you’ve
worked with a collection of Field objects (a recordset’s Fields collection).
These differences aside, there are really four different things you’ll want to do
with collections:
1. Put objects into them (Add method). Sometimes you can add items to a
collection directly using a method of the collection. Other times, some
action you take adds an object to a collection. For example, opening a
Visual Basic form at run time adds a Form object to the Forms collection.
2. Get objects out of them (Remove method). This is basically the opposite
of the previous action. Again, sometimes you remove objects directly,
sometimes indirectly.
3. Refer to objects in them (Item method). Once an object has been added
to a collection you can refer to it (and its properties and methods) while
it’s in the collection. Usually you do this by using the Item method of the
collection.
TIP: Collections can contain anything except user-defined types (discussed in our
chapter on the Windows API). You can have collections containing strings,
TextFile objects, Recordset objects, forms, or anything else you like.
2. Use the Dir function to retrieve file names, one at a time, from the current
folder.
3. For each file found, create a TextFile object, and open the text file.
5. Once the code finished looping through the folder, calling Dir for each file,
mcolFiles contains one object for each file found.
6. The code loops through the collection, displaying the Name and Size
property for each TextFile object in the grid on the form.
7. The code uses the collection’s Count property to display a count of found
files on the form.
Creating a Collection
You create a collection by creating a new instance of VBA’s Collection object,
like this:
You declared the collection in the Declarations section of the directory form,
frmDirList, so you could reference it from multiple event procedures:
When you click the Display button, the form instantiates the Collection object:
TIP: If mcolFiles already contained items, setting it equal to a new collection will
destroy all those existing items.
The Dir function is an odd one—it works unlike any other VBA function. If you want
to retrieve a list of files matching a file specification, follow these steps:
2. Dir returns the name of the file it found (without the path portion). If it didn’t find
a file at all, it returns an empty string. This means you can perform a loop that
runs until the return value from Dir is an empty string:
Do While Len(strFileName) > 0
3. Within the Do...Loop, process the file, and then call Dir again, but this time, send
no parameters at all. This will find the next matching file, continuing the previous
search.
4. Loop until you run out of file names—that is, until Dir returns a zero-length
string.
If you only pass a reference to the object, then the only way you can refer to it
later on is by its numeric position in the collection. It’s preferable, however, to
refer to objects by name or other string value. You can pass a unique key as the
second argument to accomplish this.
TIP: Attempting to add two items to the same collection with the same key value
will trigger a run-time error.
Our sample application uses a TextFile object’s Name property as the unique
key for the collection. The relevant portion of the code that adds each file to
the collection is shown below:
Dim tf As TextFile
Dim strFileName As String
TIP: You can also use a regular For...Next loop to enumerate items in a collection.
Set up a loop from 1 to the value returned by the collection’s Count property.
Use the Item method, explained next, to refer to objects based on their
position in the collection. This technique is, however, slower than using For
Each...Next.
lblFileCount.Caption = _
mcolFiles.Count & " files found."
position in the collection or its unique key. For instance, you can refer to a
TextFile object in the mcolFiles collection in any of these ways:
Dim tf As TextFile
Set tf = mcolFiles.Item(1)
Debug.Print tf.FileName
Debug.Print mcolFiles.Item(1).FileName
Debug.Print mcolFiles.Item("TextFile.cls").FileName
Since Item is the default method of the Collection object, you can shorten the
code above to this:
Debug.Print mcolFiles(1).FileName
Debug.Print mcolFiles("TextFile.cls").FileName
The example uses the Item method of the Collection object in the Click event
of the form’s grid control to display the full path to a file in the collection:
intRow = grdFiles.Row
Set tf = mcolFiles.Item(intRow)
MsgBox "You selected " & tf.FileName
End Sub
mcolFiles.Remove 1
' or
mcolFiles.Remove "TextFile.cls"
This is the first thing the example does when you click the Display button.
Although you can remove all the items, one by one, there’s no point.
Reinitializing the Collection object is the correct way to do it.
To remove all the items and release the memory used by the Collection object,
use code like this:
Summary
• A collection is an organized group of objects that features methods for
adding, removing, and referring to objects.
• You can use the VBA Collection object to store other objects.
• The VBA Collection object has three methods (Add, Remove, and
Item) and one property (Count).
• You add an object to a collection by instantiating it separately and then
passing the object variable to the Add method.
Questions
1. True or False? Objects in a collection are usually of the same type.
2. What are the two ways you can refer to objects in a collection?
Answers
1. True or False? Objects in a collection are usually of the same type.
True
2. What are the two ways you can refer to objects in a collection?
By position or by unique identifier
Lab 19:
Working with
Collections
TIP: Because this lab includes a great deal of typed code, we’ve tried to make it
simpler for you. You’ll find all the code in COLLECTIONS.TXT, in the
same directory as the sample project. To avoid typing the code, you can
cut/paste it from the text file instead.
Lab 19 Overview
In this lab you’ll learn how to manipulate and create collections of objects.
You’ll work with some built-in collections as well as those you create yourself.
Objective
In this section you will manipulate a built-in Visual Basic collection, the
Controls collection. In the sample project (Collections1.VBP) we’ve provided
a form (frmCollections) that contains several text boxes. Your goal: When a
button is clicked, use the form’s Controls collection to make sure that none of
the text boxes are left blank.
Things to Consider
• How do you refer to each item in a collection?
• How can you tell if a control is a text box?
• How can you tell if a text box contains text?
Step-by-Step Instructions
1. Launch Visual Basic and open the project file COLLECTIONS1.VBP.
Figure 2. Add code to this form to make sure all the text boxes are filled in.
3. Double-click the Save button. Visual Basic displays the form’s module
window with an empty procedure for the button’s Click event.
6. Verify that the program works as expected by filling in some, but not all of
the text boxes, and clicking the Save button. Visual Basic should display a
dialog box, warning that you must fill in all the text boxes. The form then
sets the focus back to the first empty text box in the collection of controls
(this may not be the first empty textbox, top-to-bottom).
7. When you are finished experimenting, stop the program and save the
project.
Objective
In this section you’ll create a new collection of your own using the VBA
Collection object. In the second sample project (COLLECTIONS2.VBP)
we’ve created a form (frmFish, shown in Figure 3) with several text boxes that
correspond to properties of a user-defined class named Fish (this simple class
is completed already for you). You’ll add code that defines a collection and
creates new instances of the Fish class and add them to the collection. You’ll
need to solve these problems:
Things to Consider
• How do you define a custom collection?
• How do you instantiate a custom class?
Step-by-Step Instructions
1. Open the sample project file for this section, COLLECTIONS2.VBP.
2. Select the frmFish form in the Project window and press F7 to open the
form’s module window.
3. In the declarations section of the module, type the following line of code:
5. Select cmdAdd from the Object list at the top of the module window.
Visual Basic creates an empty procedure for the cmdAdd button’s Click
event.
objFish.Name = txtName.Text
objFish.Species = txtSpecies.Text
objFish.Color = txtColor.Text
txtName.Text = ""
txtSpecies.Text = ""
txtColor.Text = ""
End Sub
7. Select cmdFind from the Object list at the top of the module window.
Visual Basic creates an empty procedure for the cmdFind button’s Click
event.
If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If
10. Verify that the code works by adding a new fish to the collection. Fill in
values in each text box (see Figure 4) and click the Add button.
Figure 4. Add a fish by typing in values and clicking the Add button.
11. Type the number 1 into the Name or number text box and click the Find
button. Visual Basic should display a dialog box displaying the fish you
found. (Note that the Delete button does nothing at the moment.)
WARNING! If you click the Find button without adding any fishes, or with
nothing in the Name or number text box, you’ll receive an error
message. We’ll discuss, in the next section, how to deal with this
problem.
13. Make sure the form’s code window is displayed and select cmdDelete
from the Object list. Visual Basic creates an empty procedure for the
button’s Click event.
If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If
mcolFishes.Remove varKey
End Sub
16. Verify that the code works by adding at least two fish to the collection.
Then type the number 1 into the Name or number text box and click the
Find button. Visual Basic displays information about the first fish that you
added.
17. Click the Delete button and then the Find button again. This time Visual
Basic displays information on the second fish, which is now fish number 1.
18. When you have finished experimenting, stop the program and save the
project.
Objective
In this exercise you’ll add error handling to procedures that manipulate
collections. It’s all too easy to request an item by name or by number that
doesn’t exist in the collection, and doing so raises a run-time error. This means
you need to trap for errors in procedures that use the Item or Remove methods
of the VBA collection object. In those procedures, add error handling that
gracefully alerts the user to the situation, but doesn’t cause the application to
fail.
Things to Consider
• How do you set an error trap?
• How do you display the message associated with the current run-time
error?
Step-by-Step Instructions
1. With the project in design mode, open the module window for the form.
If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If
ExitHere:
Exit Sub
HandleErrors:
MsgBox "Invalid fishie!", vbExclamation
Resume ExitHere
End Sub
If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If
mcolFishes.Remove varKey
ExitHere:
Exit Sub
HandleErrors:
MsgBox "Invalid fishie!", vbExclamation
Resume ExitHere
End Sub