Вы находитесь на странице: 1из 39

Programming

Visual Basic 6.0


Applications

Level 2
Table of Contents

Programming Visual Basic 6.0 Applications


Table of Contents

INTRODUCTION .................................................................................... INTRO-1


A Few Words About This Courseware......................................... INTRO-2
World-Class Courseware Taught by World-Class
Instructors....................................................................... INTRO-2
What We Expect of You................................................... INTRO-2
What Youll Get Out of this Class..................................... INTRO-2
Courseware Conventions................................................. INTRO-3
The Practice Files........................................................................ INTRO-4
About the Author ......................................................................... INTRO-5

AN INTRODUCTION TO OBJECTS ...............................................................13-1


What Is an Object?..............................................................................13-2
Using Properties and Methods in Code....................................13-2
The Object Browser.............................................................................13-4
Using the Object Browser ........................................................13-4
Parts of the Object Browser .....................................................13-5
System Objects ...................................................................................13-7
Screen Object..........................................................................13-8
Determining the Screen Coordinate System ............................13-8
Introducing Object Variables .............................................................13-10
Why Use Object Variables? ...................................................13-10
Object Variables vs. Simple Variables ...................................13-11
Assigning an Object Variable .................................................13-12
Theres Still Another Way: WithEnd With............................13-13
What About Uninitialized Object Variables? ...........................13-14
Classifying Objects............................................................................13-16
Working with Forms ...............................................................13-17
Working with Controls ............................................................13-18
Specific Object Types ............................................................13-19
Which Is Better: Specific or Generic?.....................................13-22
Referring to Objects ..........................................................................13-23
Its Just Syntax.......................................................................13-23
Using the Global Forms Collection ....................................................13-26
Whats a Collection? ..............................................................13-26
Using For EachNext ...........................................................13-26
Using the Forms Collection....................................................13-27

Programming Visual Basic 6.0 Applications TOC-1


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Working with External Objects...........................................................13-29


Setting the Reference ............................................................13-29
Creating an Instance of an Object..........................................13-31

LAB 13: AN INTRODUCTION TO OBJECTS...............................................13-37


Lab 13 Overview ...............................................................................13-38
Create a Modal About Form ............................................................13-39
Work with Controls and Fonts............................................................13-43

MANAGING DATA WITH ADO .......................................................................14-1


What Is ADO? .....................................................................................14-2
Where Can You Use ADO? .....................................................14-2
Technologies at Work ..............................................................14-3
Getting Started with ADO ....................................................................14-5
Initial Steps ..............................................................................14-5
Which Version of ADO? ...........................................................14-5
The Recordset Object ..............................................................14-6
Creating a Simple Recordset ...................................................14-6
A Few Issues ...........................................................................14-8
The ADO Object Hierarchy................................................................14-12
The ADO Connection Object .............................................................14-13
Looping Through All the Fields ..............................................14-15
Working with Recordset Properties and Methods ..............................14-16
Are There Any Rows?............................................................14-16
Moving Through a Recordset.................................................14-17
Types of Recordsets..............................................................14-20
How Many Rows Are There? .................................................14-21
Creating Recordsets Based on a SQL String .........................14-21
The Command Object .......................................................................14-23
Creating a Command Object..................................................14-23
Command Object Properties..................................................14-23
Using a Command Object with Parameters ...........................14-24
What About Finding Rows? ...................................................14-27
Updating Recordset Data ..................................................................14-28
The LockType Property..........................................................14-28
Updating Records ..................................................................14-29
Adding Records .....................................................................14-31
Deleting Records ...................................................................14-33
More Command Objects Examples (On Your Own) ..........................14-34
Working with Multiple Parameters..........................................14-34

TOC-2 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Executing Bulk Updates.........................................................14-35

LAB 14: MANAGING DATA WITH ADO.......................................................14-41


Lab 14 Overview ...............................................................................14-42
Retrieve Data Using a Recordset Object ...........................................14-43
Use a Command Object ....................................................................14-47

ADO AND UNBOUND FORMS.......................................................................15-1


Forms and ADO ..................................................................................15-2
The Sample Form ....................................................................15-2
Getting Started ........................................................................15-2
Displaying Data on the Form ...............................................................15-6
Keeping Track of State ............................................................15-6
What If There Arent Any Rows?..............................................15-9
Navigating Rows......................................................................15-9
Changing Data on the Form ..............................................................15-11
Editing Data ...........................................................................15-11
Starting to Add a Row ............................................................15-11
Saving Data Back to the Recordset .......................................15-13
Finishing the Add/Edit Process ..............................................15-15
Canceling Changes ...............................................................15-19
Deleting a Row ......................................................................15-19
Why Set the Bookmark Equal to Itself?..................................15-20
Finding Data on the Form..................................................................15-22
Where Does the Find Method Start?......................................15-22
The Problem CaseApostrophes in Strings..........................15-22
Failed Searches and Record Location ...................................15-24
Using a Default Recordset.................................................................15-26
Loading the State Combo Box ...............................................15-26
Positioning the Combo Box....................................................15-27
Maintaining State Information............................................................15-29
Text and Check Boxes...........................................................15-29
The Shared Procedure, HandleChange .................................15-29
Changes in a Combo Box ......................................................15-30
Managing the Button State ....................................................15-31
Handling Navigation Buttons..................................................15-32

LAB 15: ADO AND UNBOUND FORMS ......................................................15-37


Lab 15 Overview ...............................................................................15-38
Modify the Demo Form ......................................................................15-39

Programming Visual Basic 6.0 Applications TOC-3


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

USING UI DATA TOOLS ................................................................................16-1


Whats Wrong with the ADO Data Control? .........................................16-2
Taking Advantage of the Data Environment ........................................16-3
Getting Started with the Data Environment Designer ...............16-4
Setting Up a Connection Object...............................................16-5
Creating a Command Object....................................................16-7
Data Environment and Forms ..................................................16-9
In Review ...........................................................................16-11
The Hierarchical FlexGrid Control .....................................................16-12
Add a Child Command to the Customers Command
Object ....................................................................................16-12
Getting Started with the MSHFlexGrid Control.......................16-13
Using the MSHFlexGrid Control.............................................16-14
Creating Reports in Visual Basic .......................................................16-18
Creating a Simple Report.......................................................16-18
Using the Function Control ....................................................16-22
More Advanced Uses for the Data Environment Designer
(On Your Own) ..................................................................................16-24
Creating Aggregates..............................................................16-24
Grouping Data in the Data Environment ................................16-25

LAB 16: USING UI DATA TOOLS................................................................16-31


Lab 16 Overview ...............................................................................16-32
Create ADO Objects with the Data Environment Designer ................16-33
Use the Hierarchical FlexGrid Control ...............................................16-39
Create a Data-Bound Report.............................................................16-44

USING FORM MODULES ..............................................................................17-1


Whats a Form?...................................................................................17-2
Adding Form Methods .........................................................................17-3
Adding Form Properties.......................................................................17-5
Using Public Variables .............................................................17-5
Property Procedures to the Rescue .........................................17-6
Introducing Property Procedures .............................................17-6
Migrating Public Variables to Property Procedures ..................17-8
Initializing Property Values.....................................................17-10
Implementing Dialog Boxes...............................................................17-11
How It Works .........................................................................17-12
Reviewing the Steps ..............................................................17-15
Creating Multiple Instances of a Form ...............................................17-16

TOC-4 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Creating an Instance of a Form..............................................17-16


Whats Going On? .................................................................17-17
Life Cycle of a Form ..........................................................................17-21
Why Should You Care? .........................................................17-21
Created, but Not Loaded or Shown........................................17-21
Created and Loaded, but Not Shown .....................................17-22
Created, Loaded, and Shown ................................................17-22
Created and Loaded, but Not Shown (again) .........................17-23
Created, but Not Loaded or Shown (again)............................17-23
Memory and Resources Completely Reclaimed.....................17-23
Prove It to Yourself ................................................................17-24

LAB 17: USING FORM MODULES ..............................................................17-29


Lab 17 Overview ...............................................................................17-30
Create Multiple Form Instances.........................................................17-31
Create a New Form Property.............................................................17-33
Create a Form Method ......................................................................17-37
Close All Form Instances...................................................................17-40

CREATING YOUR OWN OBJECTS ...............................................................18-1


Introduction to Class Modules .............................................................18-2
Create Your Own Objects ........................................................18-2
Why Would You Do This?........................................................18-2
Its Cookie Cutter Time ............................................................18-3
Creating a Class Module..........................................................18-3
Creating Simple Properties ......................................................18-5
Creating Instances of the Class ...............................................18-5
Creating and Using Methods....................................................18-7
Creating Multiple Instances......................................................18-8
Starting and Stopping........................................................................18-10
Initialize and Terminate Events ..............................................18-10
Properties Arent Always So Simple ..................................................18-11
Why Not Use Public Variables? .............................................18-11
Using Property Get ................................................................18-11
Initializing Property Values.....................................................18-12
Using Property Let .................................................................18-12
Important Considerations.......................................................18-13
A Simple, Useful Class......................................................................18-14
Measuring Time .....................................................................18-14

Programming Visual Basic 6.0 Applications TOC-5


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

TextFile: Working with Text Files.......................................................18-17


Using the TextFile Class ........................................................18-18
Working with TextFiles...........................................................18-19
Using the Class Builder .....................................................................18-22

LAB 18: CREATING YOUR OWN OBJECTS...............................................18-29


Lab 18 Overview ...............................................................................18-30
Create the File Class.........................................................................18-31
Handle the File Objects Properties ...................................................18-35
Finish the File Object and Test It .......................................................18-38
Call the File Object from a Form........................................................18-40

WORKING WITH COLLECTIONS ..................................................................19-1


Collection Overview.............................................................................19-2
What Is a Collection?...............................................................19-2
Using a Collection....................................................................19-2
Using the Collection Object .................................................................19-4
Collecting TextFile Objects ......................................................19-4
How the Example Works..........................................................19-5
Creating a Collection ...............................................................19-5
Adding Items to a Collection ....................................................19-6
Enumerating Objects in a Collection ........................................19-8
Determining the Number of Items in a Collection .....................19-8
Referring to Objects in a Collection..........................................19-8
Removing an Item from a Collection ........................................19-9
Removing All Items from a Collection ....................................19-10

LAB 19: WORKING WITH COLLECTIONS..................................................19-15


Lab 19 Overview ...............................................................................19-16
Manipulate a Built-In Collection .........................................................19-17
Create a New Collection....................................................................19-19
Add Error Handling............................................................................19-24

CREATING MDI APPLICATIONS ...................................................................20-1


What Is MDI? ......................................................................................20-2
How About SDI? ......................................................................20-3
Run-Time Behavior of MDI Child Forms...................................20-3
Creating an MDI Application................................................................20-4
Creating an MDI Form .............................................................20-4
Creating a Child Form at Design Time .....................................20-4

TOC-6 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Creating a Child Form Instance at Run Time ...........................20-5


Creating a Window List ............................................................20-7
Arranging Child Windows.........................................................20-8
Positioning Child Forms ...........................................................20-9
What If Theres No Child Open? ............................................20-10
Working with MDI Applications ..........................................................20-12
Maintaining State Information ................................................20-12
Unloading MDI Forms............................................................20-12
UnloadMode Values ..............................................................20-13
Menus in MDI Applications ....................................................20-14
Non-MDI Child Modal Forms..................................................20-15
Using Windows Common Controls ....................................................20-17
Adding Common Controls......................................................20-17
The ImageList Control............................................................20-17
The Toolbar Control...............................................................20-19
The StatusBar Control ...........................................................20-24
Panel Styles...........................................................................20-26
Understanding AutoSize ........................................................20-26

LAB 20: CREATING MDI APPLICATIONS ..................................................20-31


Lab 20 Overview ...............................................................................20-32
Create the MDI Parent and Child Forms............................................20-33
Create the Window Menu ..................................................................20-36
Handle Modified Child Forms ............................................................20-39

WORKING WITH THE WINDOWS API...........................................................21-1


What Is the Windows API? ..................................................................21-2
External Functions Provide Flexibility.......................................21-2
Introducing the DLL (Dynamic Link Library) .............................21-2
Windows Itself Is Composed Mostly of DLLs ...........................21-2
Uses for the Windows API .......................................................21-3
API Declarations .................................................................................21-4
The Declare Statement ............................................................21-4
When Do You Use ByVal?.......................................................21-6
Why Use an Alias? ..................................................................21-6
Heed this Warning! ..................................................................21-7
Using the API Viewer/WIN32API.TXT .................................................21-8
Using the API Viewer ...............................................................21-8
Using Win32API.TXT ...............................................................21-9
What if You Dont Know What You Need? ...............................21-9

Programming Visual Basic 6.0 Applications TOC-7


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

A Few Simple Examples....................................................................21-10


Using the API timeGetTime Function .....................................21-10
Flash a Windows Caption .....................................................21-12
Declaring User-Defined Data Types ..................................................21-15
Referring to Elements of a User-Defined Type.......................21-15
Using a User-Defined Data Type ...........................................21-16
Working with Strings..........................................................................21-18
Talking to Controls (Using SendMessage) ........................................21-20
Using SendMessage..............................................................21-20
Limit the Text Entered in a Combo Box..................................21-21
Resources.........................................................................................21-23

LAB 21: WORKING WITH THE WINDOWS API ..........................................21-27


Lab 21 Overview ...............................................................................21-28
Use SendMessage to Force a Combo Box to Drop ...........................21-29
Retrieve the Computer Name............................................................21-31
Use a User-Defined Type to Retrieve Memory Status .......................21-33

OPTIMIZING VISUAL BASIC PROGRAMS ....................................................22-1


Getting Started with Optimization ........................................................22-2
Know Where to Start................................................................22-2
Know Where to Stop................................................................22-2
Testing Hypotheses.............................................................................22-3
Where Do You Look? ..........................................................................22-5
Optimizing Code Speed.......................................................................22-6
Use Longs Rather than Variants ..............................................22-6
Use Len to Test for Zero-Length Strings ..................................22-6
Use Var = Not Var to Toggle True/False................................22-6
Use timeGetTime Instead of Timer ..........................................22-7
Use Object Variables/WithEnd With .....................................22-8
Avoid Concatenation................................................................22-9
Avoid IIf ...................................................................................22-9
Use vbNullString Rather Than "" To Initialize Strings .............22-11
Avoid Retrieving Property Values ..........................................22-11
Use Early Binding if Possible .................................................22-12
Optimizing Display Speed .................................................................22-13
Set ClipControls Property Correctly .......................................22-13
Set AutoRedraw Correctly .....................................................22-13
Use Image Controls if Possible ..............................................22-14

TOC-8 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Hide Controls to Avoid Multiple Repaints ...............................22-14


Use the Move Method............................................................22-14
Optimizing Apparent Speed...............................................................22-15
Keep Forms Hidden, But Loaded...........................................22-15
Preload Data..........................................................................22-15
Use Timers to Work in the Background..................................22-15
Use Progress Indicators.........................................................22-17
Optimizing Size in Memory................................................................22-18
Reclaim Memory....................................................................22-18
Remove Dead Code ..............................................................22-19

LAB 22: OPTIMIZING VISUAL BASIC PROGRAMS....................................22-23


Lab 22 Overview ...............................................................................22-24
Test a Code Speed Hypothesis .........................................................22-25
Compare Early Binding to Late Binding .............................................22-29
Compare Native Code to p-Code Compiling......................................22-32

ADDING PROFESSIONAL TOUCHES ...........................................................23-1


Storing Program Options .....................................................................23-2
Using the Windows Registry ....................................................23-2
An Example .............................................................................23-4
Using the Common Dialog Control ......................................................23-7
What Does It Offer? .................................................................23-7
Using the Control .....................................................................23-7
File Open/File Save .................................................................23-8
Font Selection........................................................................23-10
Color Selection ......................................................................23-13
Canceling the Dialog Box.......................................................23-14
Adding Standard Forms.....................................................................23-16
Adding Forms from Templates...............................................23-16
Adding a Splash Screen ........................................................23-16
Adding an About Dialog Box ..................................................23-19
Other Forms ..........................................................................23-19
Creating Your Own Templates ..........................................................23-21
Different Template Types.......................................................23-21
What Makes a Good Template ..............................................23-21
Creating a Template ..............................................................23-21

LAB 23: ADDING PROFESSIONAL TOUCHES ..........................................23-27


Lab 23 Overview ...............................................................................23-28

Programming Visual Basic 6.0 Applications TOC-9


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Save and Retrieve Program Settings.................................................23-29


Use the Common Dialog Control .......................................................23-32
Create a Form Template ...................................................................23-36

APPENDIX A: THE REDDICK VBA NAMING CONVENTIONS ....................... A-1


Introduction .......................................................................................... A-2
Changes to the Conventions..................................................... A-2
An Introduction to Hungarian................................................................ A-3
Tags ......................................................................................... A-3
Creating Data Types................................................................. A-6
Constructing Procedures .......................................................... A-8
Prefixes .................................................................................... A-9
Suffixes................................................................................... A-11
File Names ............................................................................. A-11
Host Application and Component Extensions to the
Conventions............................................................................ A-12

APPENDIX B: USEFUL VBA FUNCTIONS...................................................... B-1


Lots of Functions to Choose From........................................................ B-2
Strings ...................................................................................... B-2
Dates and Times....................................................................... B-3
Conversion ............................................................................... B-3
Other ........................................................................................ B-4
New in Visual Basic 6.0 ............................................................ B-4

APPENDIX C: USEFUL SHORTCUTS ............................................................ C-1


Table of Shortcut Keys ......................................................................... C-2
Design Environment ................................................................. C-3
Debugging ................................................................................ C-3

APPENDIX D: MORE API EXAMPLES............................................................ D-1


Using the AddressOf Operator ............................................................. D-2
Set Tabstops in a List Box.................................................................... D-6
Scroll a Multiline Text Box .................................................................... D-8
Detecting Whether a Specific App Is Loaded...................................... D-10
Finding a Running Application ................................................ D-10
Using Class Names ................................................................ D-10
Using Null Strings in API Calls ................................................ D-11
Starting Another Application.................................................... D-12

APPENDIX E: USING DRAG AND DROP ....................................................... E-1

TOC-10 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Whats Drag and Drop?........................................................................ E-2


Using Visual Basics Drag and Drop..................................................... E-3
Using the DragDrop Event ........................................................ E-3
Using Manual DragMode .......................................................... E-5
Changing the Drag Icon ............................................................ E-6
Changing the Icon in Code ....................................................... E-7
Really Using Drag and Drop ..................................................... E-8
Using Windows OLE Drag and Drop.................................................. E-13
Digging in Deeper ................................................................... E-14
Making It Happen.................................................................... E-14

APPENDIX F: USING WINDOWS COMMON CONTROLS ............................. F-1


The Windows Common Controls .......................................................... F-2
The Common Controls.............................................................. F-2
Available Common Controls...................................................... F-2
User Interface Consistency..................................................... F-12
Collections of Objects ............................................................. F-12
The ImageList Control ........................................................................ F-14
Managing Images ................................................................... F-14
The Toolbar Control ........................................................................... F-17
The Style Property .................................................................. F-20
Handling Button Clicks............................................................ F-23
Handling ButtonMenu Clicks................................................... F-24
Controlling the Drop-Down Menu ............................................ F-25
Handling Controls and PlaceHolder Buttons ........................... F-27
The StatusBar Control........................................................................ F-28
Designing a StatusBar ............................................................ F-28
Panel Styles............................................................................ F-29
Understanding AutoSize ......................................................... F-30
Responding to PanelClick Events ........................................... F-31
The ProgressBar Control.................................................................... F-33
Controlling the Appearance of a ProgressBar ......................... F-33
Manipulating the Progress Meter ............................................ F-35
The TreeView Control ........................................................................ F-37
Managing Nodes..................................................................... F-37
TreeView Events..................................................................... F-40
The ListView Control .......................................................................... F-44
ListView Styles........................................................................ F-44
Managing ListView Information ............................................... F-45

Programming Visual Basic 6.0 Applications TOC-11


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Sorting Columns ..................................................................... F-47

LAB F: USING WINDOWS COMMON CONTROLS...................................... F-53


Lab F Overview .................................................................................. F-54
Create a Status Bar............................................................................ F-55
Create a Toolbar ................................................................................ F-61

APPENDIX G: SETTING UP THE ENVIRONMENT.........................................G-1


Global Settings in Visual Basic .............................................................G-2
Setting IDE Properties..........................................................................G-3
Setting Up Windows .............................................................................G-5

INDEX......................................................................................................INDEX-1

TOC-12 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

Working with
Collections
Objectives
Introduce how collections work.
See how to use the VBA Collection object.
Create a collection containing user-defined TextFile objects.

The sample project for this chapter is COLLECTIONS.VBP.

Programming Visual Basic 6.0 Applications 19-1


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

Collection Overview
Before you learn how to create your own collections, lets 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

Collection An object that is itself a container for other objects. Objects in a


collection are usually of the same type.

Using a Collection
Youve 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 youve worked with ADO, youve
worked with a collection of Field objects (a recordsets Fields collection).

As youll see in a moment, VBA implements a specific Collection object with


a specific set of properties and methods. In general, however, general
collections (such as Forms, Controls, and Fields) offer a variety of ways to
work with the collection and the objects it contains. It is often up to the
developer as to how to implement a collection (that is, the Microsoft developer
who wrote ADO, or Visual Basic), so the general collections you work with
may do things differently.

These differences aside, there are really four different things youll want to do
with collections:

19-2 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Collection Overview

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
its in the collection. Usually you do this by using the Item method of the
collection.

4. Count the number of objects in them (Count property). All collections


implement a Count property that tells you how many objects they contain.

Programming Visual Basic 6.0 Applications 19-3


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

Using the Collection Object


VBA allows you to create your own collection objects by using a type of
object named, appropriately, Collection. Methods of the Collection object
allow you to add, remove, and refer to objects. Collections can even contain
other collections. You can specify a unique key value for each item in the
collection, which you can use instead of the position in the collection for
retrieving the item. (This key is write-only, and write-once. That is, theres no
mechanism for retrieving the key associated with an item, nor is there a way to
change the key once the item is in 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.

Collecting TextFile Objects


To demonstrate how to use the VBA Collection object, weve created a very
simple file directory list (shown in Figure 1). This list is populated by a
collection that you create when you click the Display button. As the example
scans the selected directory, it creates new instances of the TextFile class and
adds each instance to the collection. Once it has filled the collection, it iterates
through the collection, adding a row (containing the Name and Size property
of the TextFile object) to the grid for each file.

Figure 1. A simple file directory list populated by a collection of TextFile objects.

19-4 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

How the Example Works


In this simple example, youll follow these steps:

1. Create a private Collection object, mcolFiles.

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.

4. Add each TextFile object to the collection of files, mcolFiles.

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 collections 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 VBAs Collection object,
like this:

Dim col As Collection


Set col = New Collection

Once you do that, youre ready to add items.

You declared the collection in the Declarations section of the directory form,
frmDirList, so you could reference it from multiple event procedures:

Private mcolFiles As Collection

When you click the Display button, the form instantiates the Collection object:

Set mcolFiles = New Collection

Programming Visual Basic 6.0 Applications 19-5


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

TIP: If mcolFiles already contained items, setting it equal to a new collection will
destroy all those existing items.

Using the Dir Function

The Dir function is an odd oneit works unlike any other VBA function. If you want
to retrieve a list of files matching a file specification, follow these steps:

1. Call Dir, passing the file specification as the parameter.

2. Dir returns the name of the file it found (without the path portion). If it didnt 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 namesthat is, until Dir returns a zero-length
string.

Adding Items to a Collection


To add an object to a collection, you begin by declaring a new instance of that
object as a separate variable. You then pass the variable to the Collection
objects Add method. The general declaration of the Add method is shown
below:

collectionobject.Add object [, key][, before |, after]

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. Its 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.

19-6 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

Our sample application uses a TextFile objects 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

' Initialize the collection. If it


' had TextFile objects in it,
' this will destroy them all.
Set mcolFiles = New Collection

' Get the first file


strFileName = Dir(App.Path & "\*.*")
Do While Len(strFileName) > 0

' Create a new TextFile object


Set tf = New TextFile
tf.OpenTextFile App.Path & "\" & strFileName

' Add it to the collection


mcolFiles.Add tf, tf.Name

' Get the next file


strFileName = Dir()
Loop

WARNING! If youve created a public Collection object, any code, anywhere in


your project, can get to that collection, and can add anything at all to
it. In theory, this isnt a problem. But when you later use a For
Each...Next loop to visit each element of the collection, expecting to
find all objects of the same type, youre going to be surprised. In our
Level 3 course, we discuss a solution to this problem. If you want to
think ahead, the solution depends on creating a class that looks and
feels like a Collection, but only allows you to add specific types of
objects.

Programming Visual Basic 6.0 Applications 19-7


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

Enumerating Objects in a Collection


Youve already seen examples of using a For Each loop. This type of loop is
designed specifically to enumerate (loop through) items in a collection. After
building up the collection of TextFile objects, our sample application uses a
For Each loop to add information on each one to the list:

' Now, put them in the grid


For Each tf In mcolFiles
With tf
strText = .Name & vbTab & .Size
End With
grdFiles.AddItem strText
Next

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 collections 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.

Determining the Number of Items in a


Collection
Use the collections Count property to determine the number of items currently
in the collection. In the example, after filling the collection, the code sets the
Caption property of lblFileCount, like this:

lblFileCount.Caption = _
mcolFiles.Count & " files found."

Referring to Objects in a Collection


To refer to an object in a collection you use the Collection objects Item
method. The Item method accepts an argument that can either be an objects

19-8 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

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 forms grid control to display the full path to a file in the collection:

Private Sub grdFiles_Click()


Dim tf As TextFile
Dim intRow As Integer

intRow = grdFiles.Row
Set tf = mcolFiles.Item(intRow)
MsgBox "You selected " & tf.FileName
End Sub

Removing an Item from a Collection


To remove an item from a collection, use the Remove method, supplying
either the index or the unique string value. Our sample application doesnt
remove any objects from the mcolFiles collection, but if it did the code might
look like this:

Programming Visual Basic 6.0 Applications 19-9


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

mcolFiles.Remove 1
' or
mcolFiles.Remove "TextFile.cls"

Removing All Items from a Collection


To remove all the items in a collection, and start fresh, theres no faster or
better way to do it than this:

Set mcolFiles = New Collection

This is the first thing the example does when you click the Display button.
Although you can remove all the items, one by one, theres 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:

Set mcolFiles = Nothing

19-10 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

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.

Programming Visual Basic 6.0 Applications 19-11


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

(Review questions and answers on the following pages.)

19-12 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

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?

3. What must you do to refer to an object in a collection using a text string?

Programming Visual Basic 6.0 Applications 19-13


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Collections

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

3. What must you do to refer to an object in a collection using a text string?


Pass a unique identifier as the second argument to the Add
method

19-14 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Collection Object

Lab 19:
Working with
Collections
TIP: Because this lab includes a great deal of typed code, weve tried to make it
simpler for you. Youll 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.

Programming Visual Basic 6.0 Applications 19-15


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections

Lab 19 Overview
In this lab youll learn how to manipulate and create collections of objects.
Youll work with some built-in collections as well as those you create yourself.

To complete this lab, youll need to work through three exercises:

Manipulate a Built-In Collection


Create a New Collection
Add Error Handling
Each exercise includes an Objective section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.

19-16 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Manipulate a Built-In Collection

Manipulate a Built-In Collection

Objective
In this section you will manipulate a built-in Visual Basic collection, the
Controls collection. In the sample project (Collections1.VBP) weve provided
a form (frmCollections) that contains several text boxes. Your goal: When a
button is clicked, use the forms 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.

2. Double-click the frmCollections form in the Project window to display


the form shown in Figure 2.

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 forms module
window with an empty procedure for the buttons Click event.

Programming Visual Basic 6.0 Applications 19-17


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections
4. Modify the procedure so it looks like the one shown below:

' Code fragment 1.


Private Sub cmdSave_Click()
Dim ctl As Control

For Each ctl In Me.Controls


If TypeOf ctl Is TextBox Then
If Len(ctl.Text) = 0 Then
MsgBox "You must fill in all " & _
"the text boxes.", vbExclamation
ctl.SetFocus
Exit For
End If
End If
Next
End Sub

5. Press F5 to run the program.

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.

19-18 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Create a New Collection

Create a New Collection

Objective
In this section youll create a new collection of your own using the VBA
Collection object. In the second sample project (COLLECTIONS2.VBP)
weve 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). Youll add code that defines a collection and
creates new instances of the Fish class and add them to the collection. Youll
need to solve these problems:

Create a collection of Fish objects.


When you click the Add button on the form, create a new Fish object,
gather information from the forms text boxes, and add the new Fish
object to the collection of fishes.
After entering a fish name or number in the text box at the bottom of
the form, use the Find button to find the particular fish and call its
DisplayInfo method.
Finally, write code to delete the selected fish object, as well.

Figure 3. Use this form to add objects to a collection.

Things to Consider
How do you define a custom collection?
How do you instantiate a custom class?

Programming Visual Basic 6.0 Applications 19-19


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections
How do you add objects to a collection?
How do you refer to objects in a collection?
How do you remove items from a collection?

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
forms module window.

3. In the declarations section of the module, type the following line of code:

Private mcolFishes As Collection

4. To initialize the collection, add the following procedure to the forms


module:

Private Sub Form_Initialize()


Set mcolFishes = New Collection
End Sub

5. Select cmdAdd from the Object list at the top of the module window.
Visual Basic creates an empty procedure for the cmdAdd buttons Click
event.

6. Change the procedure so it looks like the following:

19-20 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Create a New Collection

' Code fragment 2.


Private Sub cmdAdd_Click()
Dim objFish As Fish

Set objFish = New Fish

objFish.Name = txtName.Text
objFish.Species = txtSpecies.Text
objFish.Color = txtColor.Text

mcolFishes.Add objFish, objFish.Name

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 buttons Click
event.

8. Change the procedure so it looks like the following:

' Code fragment 3.


Private Sub cmdFind_Click()
Dim objFish As Fish
Dim varKey As Variant

If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If

Set objFish = mcolFishes.Item(varKey)


objFish.DisplayInfo
End Sub

Programming Visual Basic 6.0 Applications 19-21


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections

9. Press F5 to run the program.

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, youll receive an error
message. Well discuss, in the next section, how to deal with this
problem.

12. Stop the program and return to design mode.

13. Make sure the forms code window is displayed and select cmdDelete
from the Object list. Visual Basic creates an empty procedure for the
buttons Click event.

14. Change the procedure so that it looks like the following:

19-22 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Create a New Collection

' Code fragment 4.


Private Sub cmdDelete_Click()
Dim varKey As Variant

If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If
mcolFishes.Remove varKey
End Sub

15. Press F5 to run the program.

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.

Programming Visual Basic 6.0 Applications 19-23


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections

Add Error Handling

Objective
In this exercise youll add error handling to procedures that manipulate
collections. Its all too easy to request an item by name or by number that
doesnt 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 doesnt 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.

2. Change the cmdFind_Click procedure to look like the following:

Private Sub cmdFind_Click()


Dim objFish As Fish
Dim varKey As Variant

On Error GoTo HandleErrors

If IsNumeric(txtFind.Text) Then
varKey = CLng(txtFind.Text)
Else
varKey = txtFind.Text
End If

19-24 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Add Error Handling

Set objFish = mcolFishes.Item(varKey)


objFish.DisplayInfo

ExitHere:
Exit Sub

HandleErrors:
MsgBox "Invalid fishie!", vbExclamation
Resume ExitHere
End Sub

3. Change the cmdDelete_Click procedure so it looks like the following:

Private Sub cmdDelete_Click()


Dim varKey As Variant

On Error GoTo HandleErrors

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

4. Press F5 to run the program.

Programming Visual Basic 6.0 Applications 19-25


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 19:
Working with Collections
5. Enter any number or text in the Name or number text box and click either
the Find or Delete button. Visual Basic will display an error message and
return to the application, rather than aborting.

6. Stop the program and save the project.

19-26 Programming Visual Basic 6.0 Applications


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.

Вам также может понравиться