During this hour you will learn
This lesson returns to some theory and hones your knowledge of Visual Basic objects. After this hour, you'll have a better understanding of objects and will better understand how objects relate to arrays and collections.
The control array is nice to use when you need to place several similar controls on a form. You need to create only one control, adjust its property values, and then create additional controls from that one (at runtime or design time). The subsequent controls contain the same property values-until you change one or more of the values. You reference the individual controls in the control array the same way you reference elements in arrays.
In this hour you also will master the Object Browser, which is a repository of object data. The Object Browser gives you an organized view of your project as well as Visual Basic's language.
In Hour 19, you learned how to use the If...Is statement to test for an object's form. This lesson further explains what If...Is does-it actually determines an object's class. If you're new to objects and classes (these terms are used in other programming languages, especially object-oriented languages), you'll learn all you need in this lesson.
An object can be just about anything in Visual Basic. You've already worked with objects such as controls, forms, and the Printer object. Also, you passed the Object data type to a procedure in Hour 19.
This topic section explains some object-related terminology and helps you view Visual Basic objects from a new perspective.
You've already seen that control objects contain properties, methods, and events. The controls contain code and data items. In a way, an object-such as the command button control-is like a package handed to you by the Visual Basic programmers. You don't have to write code to trigger a command button, declare variables that describe how a command button looks or what caption it has, and write code to perform work with a command button. The command button methods do all the work for you.
Objects are encapsulated. Like a capsule that contains medicine or lunar astronauts, an object encapsulates methods, events, and properties. This encapsulation lets you work with objects from a higher perspective than if you had to write all the code needed to support the objects.![]()
Objects not only bring encapsulation to your programming fingertips, but also are part of an object hierarchy called an object class. The benefit of a class is that all objects in the class share the same features. (A single object is said to be an instance of the class.)
You can create your own objects. By making them part of an existing class, your objects automatically gain, or inherit, many properties, methods, and events from that class.![]()
When you test an object with If...Is, Visual Basic returns the object's class. Therefore, the following returns True or False, depending on whether the object named myObj is a part of the CommandButton class:
If TypeOf myObj Is CommandButton ' Check the class
VB also supports the TypeOf() function that returns the class name. For example, TypeOf(myObj) might return CommandButton or Form.![]()
Classes make programming with objects more flexible than it would be without the class structure. For example, the With...End With statement lets you easily assign multiple properties for a single object. Notice the following code's redundancy:
chkMaster.Caption = "Primary Source" chkMaster.Alignment = vbLeftJustify chkMaster.Enabled = True chkMaster.Font.Bold = False chkMaster.Left = 1000 chkMaster.RightToLeft = False chkMaster.Top = 400
When you enclose an object inside a With...End With block, you can eliminate the repetition of the object name. The following code is identical to the previous code:
With chkMaster .Caption = "Primary Source" .Alignment = vbLeftJustify .Enabled = True .Font.Bold = False .Left = 1000 .RightToLeft = False .Top = 400 End With
Using With...End With for two or three property settings requires more typing than using straight assignments. When you need to assign more than three properties, however, the With...End With block is an appealing coding statement, because it requires less typing and is easier to maintain if you add properties and require more assignments later.![]()
Unlike the objects you declare, system objects are the Printer and Debug objects you've already used in this book. Although you can't pass system objects (they're already global in nature), you can treat them much like the objects you create. System objects represent specific elements of your application.
Table 20.1 describes the system objects and lists some important methods you can apply to them.
Table 20.1 System Objects and Their Key Methods
Object | Description | |
App | The current application. Key methods: | |
EXEName | Returns the application's file name | |
Path | Returns the application's path | |
Title | Returns the primary startup form's title bar text | |
Previnstance | Returns True or False indicating whether another copy of the application is now running | |
Clipboard | The Windows Clipboard region. Key methods: | |
Clear | Erases the Clipboard | |
GetData | Returns the graphic image stored on the Clipboard | |
GetFormat | Returns the format of the Clipboard object | |
GetText | Returns the text from the Clipboard | |
SetData | Copies a graphic image to the Clipboard | |
SetText | Copies text to the Clipboard | |
SelStart | Used for Clipboard selection operations | |
SelLength | Used for Clipboard selection operations | |
SelText | Used for Clipboard selection operations | |
Debug | The Immediate window. Key method: | |
Copies information at runtime to the immediate window (only possible in non-EXE VB programs that are run from VB's development environment) | ||
Printer | The system printer. Hour 19, "VB and the Printer," introduces the methods of the Printer object and demonstrates how they provide printer support. | |
Screen | The user's screen. Key methods: | |
FontCount | Returns the number of fonts the current screen supports | |
Fonts | Contains a list of all the screen's possible font names | |
Height | Returns the height of the screen area in twips | |
MousePointer | Holds (or determines if you specify a new one) the shape of the mouse cursor | |
TwipsPerPixelX | Returns the number of possible horizontal twips | |
TwipsPerPixelY | Returns the number of possible vertical twips | |
Width | Returns the width of the screen in twips |
You've worked with most of the system objects, especially the Printer and Screen objects, before this lesson. The App object is useful for determining runtime information about the program path and file name. The Clipboard object provides some interesting functionality you may want to use.
Depending on your application's needs, the Clipboard object is relatively simple to program. The Clipboard object is the same Clipboard that Windows uses; therefore, your application can copy or cut information to the Clipboard object and users can paste it in another Windows application. Also, your application can paste information that's contained in the Windows Clipboard into the Clipboard object.
You can use the Clipboard and its properties to select text from within your program and to determine the text selected by users. For example, the SelStart property marks the starting position of the selection cursor in the text box (or whatever control receives the selection). A value of 0 for SelStart places the cursor before the first character. SelLength determines how many characters are selected for Clipboard work. If you select text by setting SelStart and SelLength values, that text goes to the Clipboard object when users press Ctrl+C or Ctrl+X for copy or cut. SelText is a string that contains the selected text you've bounded with SelStart and SelLength.
If you've selected text in a text box control (or you've asked users to select text), that text appears in the SelText string value. You can clear the Clipboard of its current value (the Clipboard can hold only one value at a time) and send the selected text to the Clipboard with this code:
Clipboard.Clear ' Erase current Clipboard Clipboard.SetText txtName.SelText ' Copy text
If you want to copy the Clipboard text into a variable, you can use GetText() this way:
strInfo = Clipboard.GetText()
If you want to replace selected text in a control with the text on the Clipboard, you can do so this way:
txtName.SelText = Clipboard.GetText()
The GetText() method sometimes uses arguments, and requires parentheses even if you specify no arguments. For text-based Clipboard work, you don't need to supply any arguments.
If you use Microsoft Word, notice that the last statement mimics Word's Replaces Selection feature.![]()
One of the most interesting things you can do with objects is to declare an array of objects. For example, you can declare an array of command buttons or forms. Moreover, these objects don't even have to exist. For example, you don't have to declare all forms at design time, but at runtime you can still create an array of forms.
You already know about the Forms and Printers collections. Visual Basic also supports the Controls collection that lets you step through all your Controls as though they were array variables. For example, the following code hides all controls:
For intCtr = 0 to Controls.Count - 1 Controls(intCtr).Visible = False Next intCtr
If your application contains multiple forms, you can hide all controls on all forms by nesting the loop like this (notice that the For Each eliminates the Count - 1 requirement):
Dim frmAForm As Form Dim ctlAControl As Control For Each frmAForm In Forms ' Step through all forms For Each ctlAControl In frmAForm.Controls ctlAControl.Visible = False Next ctlAControl Next frmAForm
A menu is considered a control in the Controls collection. In many situations, you'll want to omit the menu controls in such a loop by testing with the TypeOf() function to determine whether the control is a Menu object before setting its visibility to False.![]()
Whereas the Controls collection holds all controls on your current form, you can declare a control array to hold one specific type of control. Declare an array of controls as follows:
Dim ctlManyLabels(1 To 4) As Label
The next topic section discusses collections further. Collections work a lot like arrays in that you can access individual elements in the collections just as you can with arrays. You might want to create an array of objects such as forms and controls. Rather than create the objects at design time, you can create the objects in an array as follows (notice the New keyword):
Dim frmArray(1 To 10) As New frmFirstForm
This Dim statement assumes that one form, frmFirstForm, exists. After the declaration, 10 new forms exist, subscripted from frmArray(1) to frmArray(10). Subsequent code can then change the form properties of the forms in the array to make each form different from the base form named frmFirstForm.
None of these forms will appear until you invoke their Show methods.![]()
Suppose that you want to decrease the font size of a form's controls if users resize a maximized form. You can use the Controls collection to decrease the font size of all controls:
Private Sub Form_Resize () ' Decrease all the controls' font size Dim intCtr As Integer For intCtr = 0 to Controls.Count - 1 Controls(intCtr).FontSize = Controls(intCtr).FontSize * .75 Next intCtr End Sub
Each control's font size will now be 25 percent smaller than it was before users resized the form.
You won't see many VB programmers using control arrays when a collection exists for the same object. VB supplies predefined collections such as Forms; if you want to use control arrays, however, you have to declare array memory to hold the array contents and initialize the arrays.
VB supports one technique for control arrays that you'll find yourself using a lot, even though collections are always available to you. When you copy a control and paste that control back onto the form, VB displays the message box shown in Figure 20.1.
FIG. 20.1VB can automatically create a control array at your request.
You might wonder why you'd ever copy and paste a control, but if you need to place several command buttons or labels that all have the same format-perhaps the same font size and caption alignment-it's a helpful technique. You just create one control, set all its properties, copy that control to the Clipboard, and then paste the Clipboard contents onto the form to add as many controls as you need.
As soon as you paste the copied control, VB displays the message
box asking if you want to create a control array. If you answerYes,
VB automatically creates a control array with a name that matches
the first control. For example, if the first control is a check
box named Check1, the array
is named Check1, and the elements
begin at Check1(0) and increment
as long as you keep pasting the control.
Your code then can step through all the control array elements from Check1(0) through Check1(n) where n is the total number of Check1 controls on the form, and set properties for them.
Collections play a vital role in VB programming, as you've seen in earlier lessons and in the preceding topic section. Collections are always present. VB updates collections automatically; for example, if you add a form at runtime with the New Form declaration, VB updates the Forms collection's Count property accordingly.
The predefined collections are helpful, so why not create your own? This brief topic section introduces some factors involved in declaring your own collections.
If you create a collection, you'll need to manage the collection yourself-this takes more effort than managing the predefined collections. This topic section explains what you need to know to declare your own collections and manage them properly.
As you learned in the previous topic section, all objects belong to a class. If you know something about a class, you know something about all objects within that class. For example, if a control is a member of the CommandButton class, you know that the control supports the Click event because all CommandButton class members support the Click event.
Your own collections must be objects of the Collection class. You define collections at the module level by using the Private or Public keyword, depending on the range of procedures that need access to your collection. The following statement declares a collection named colMyCol:
Private colMyCol As New Collection
A collection works like an empty bookcase. You can add objects (such as books), remove objects, count objects, and so on. Of course a bookcase can hold more than just books. A collection can hold only one kind of item, but you can declare multiple collections that each hold different kinds of items. Here are the methods your collections can access:
As the following example shows, Visual Basic takes care of updating Count and adding items to your collections.
The code in Listing 20.1 creates a collection named Cities and adds four items (city names) to the collection.
Listing 20.1 Using Add to add items
Dim Cities As New Collection Dim intCtr As Integer ' Add items Cities.Add "Tulsa" Cities.Add "Miami" Cities.Add "New York" Cities.Add "Seattle" ' Show that there are four cities frmMyForm.Print "There are"; Cities.Count; " cities:" ' Print each city name For intCtr = 1 To Cities.Count frmMyForm.Print " "; Cities(intCtr) Next
If you run this code, the following output appears on the form:
There are 4 cities: Tulsa Miami New York Seattle
This lesson only scratches the surface of collection power. Nevertheless, you should know that you can insert items into and remove items from your collections easily and in whatever order you prefer. Remember that each item in the collection contains a subscript, starting at 1, that you use to reference a particular item. In the preceding example, Cities(1) is the first city listed in the collection named Cities. Remember that your collection index value begins at 1, not 0 as the control arrays require.
You can use a named argument (an argument in which you include the argument name followed by a special named argument assignment operator, :=) named Before to add items to a collection at the exact location you want. The following line adds a city to the beginning of the Cities collection, no matter how many cities reside in the collection to begin with:
Cities.Add "St. Louis", Before:=1
A Before position of 1 adds the items to the front of the collection. In other words, VB inserts the new item before the specified indexed item in the collection. If you included this Add method statement at the end of the code shown earlier, the output would change to this:
There are 5 cities: St. Louis Tulsa Miami New York Seattle
If you added the code line without the Before:=1 named argument, St. Louis would appear at the end of the collection.
You can remove specific items by using the Remove method. As you remove items, the remaining subscripts adjust so they always begin at 1. The following statement removes the second item (Tulsa) from the collection:
Cities.Remove 2
As your VB knowledge improves, your need for better tools grows. VB includes the Object Browser, a tool that lets you inspect variables, controls, and other objects throughout your application. VB programmers new to the Object Browser often use it much more than they initially realize they will, because its features make programming with VB much simpler.
The Object Browser is a comprehensive online reference, but it's not online in the same sense as the online help reference. The Object Browser gives you a one-stop location to hunt for objects and object information, and to jump directly to the code you need to work with next.
The Object Browser describes your application's type libraries, which are the repositories of your class information. You can use the Object Browser to access all object properties, events, and methods for your application-including objects you've created.![]()
When you first choose Object Browser from the View
menu or click the toolbar's Object Browser button, you see the
Object Browser window (see Figure 20.2). You may have to expand
your window and close the Properties window and Toolbox to see
the full Object Browser.
The Object Browser describes your application's objects.
Table 20.2 describes the parts of the Object Browser window.
Table 20.2 Parts of the Object Browser Window
Component | Description |
Project/Library list box | Describes the source of the objects you want to browse (you'll generally browse the <All Libraries> option, but you can browse, for example, the objects in a particular project by selecting your project's name) |
Search text | Lets you enter an object, event method, or property to search for |
Maneuver controls | Used to jump back and forth along a browsing path you've previously traveled |
Classes | Holds the class names from the project or library you've selected |
Members | Contains the members for the class you've selected |
The Object Browser contains much of the same information as the online help system. The Object Browser, however, specifically targets the VB programmer and offers succinct information that's needed often. For example, the <globals> entry in the Classes list describes all of VB's built-in functions. Scroll down to the Left entry to learn about the Left() function.
As you learned in Hour 14, "Using the Supplied Functions," the Left() function returns the left part of a string.![]()
When you highlight the Left entry, VB describes the function at the bottom of the Object Browser window. The text not only describes the function's purpose but also shows the function's syntax. You can tell the nature of each object listed in the Members drop-down list by its icon. The small green icon indicates that the member is a function. You can spot collections (look at the Forms entry) and named literals by their respective icons. Scroll down to see the entire list of named literals that appears below the functions and collections in the Members scrolling list.
If you right-click either list and select Group Members
from the pop-up menu, Visual Basic groups all members and classes
by their purpose. Therefore, rather than have the literals appear
in alphabetical order, the Object Browser displays all the named
literals together, all the events together, and so on.
After you highlight any entry in an Object Browser window, click the toolbar's Help button (the icon is a question mark) to get online help on that object.![]()
You can get even more specific with the Object Browser. For example, the Classes list contains several entries that reference constants (another term for literals). When you click the ColorConstants entry, for example, only VB's color constants appear in the Members list (see Figure 20.3).
The object search has been narrowed to particular constants.
You may use these named literals anywhere in code that you need a color. For example, you can set a form's background color this way:
Notice that all the controls available in the Toolbox also appear in the Classes list. If you click on ComboBox, for example, the Object Browser displays all pertinent information for combo boxes, including properties, events, and methods. If you click one of the combo box entries in the Members list, you get a description of that method, event, or property.
People use the Object Browser for many different purposes. Keep in mind that the Object Browser displays object information in an organized manner. In addition to objects, it coordinates all your programming specifics. For example, if you're writing code that takes advantage of the built-in date and time functions, click the Object Browser's Classes entry labeled DateTime. As Figure 20.4 shows, the Members list is updated to show you only those built-in functions related to dates and times.
It's easy to find the built-in functions for a certain topic.
Although these functions are listed in the online help guide and are also available from other locations in the Object Browser (such as in the Classes entry named <globals>), reviewing the group of date and time functions makes programming with those functions simple because all the functions are referenced here in one location.
Remember that the Go Back maneuver button retraces your steps through the Object Browser, so it's easy to move back and forth with the mouse.![]()
The Object Browser is very useful for describing your own project. As you add objects, variables, and event procedures to your application, the Object Browser sits in the background filing everything. Figure 20.5 shows the Object Browser with Project1 selected for the Project/Library. When Form1 (the only user-placed object in this project so far) is clicked, the Object Browser displays a list of all the event procedures, methods, and properties for that form. Only one entry, Command1_Click, is boldfaced, meaning that code has been added only to that event procedure so far.
The Object Browser shows only active features of the application.
One of the most powerful aspects of the Object Browser is the
View Definition option. If you highlight a member that's
one of your own objects, such as an event procedure you've written
or an object you've declared, right-click the object and choose
View Definition. VB jumps directly to the code where you've
defined that object! Therefore, you can use the Object Browser
to locate specific code within a large application. You don't
have to know which project an object was defined in, as long as
you can locate the object in the Object Browser.
When you search for an item with the Object Browser, you get a list of every reference to that item within your entire application. For example, if you search for Click, VB displays an extra window (see Figure 20.6) that contains every relevant reference in the entire project (and in the entire VB repertoire, because the <All Libraries> option is selected in the Library/Project drop-down list).
The search feature has found all occurrences of Click.
The Click event occurs for several objects, so the Object Browser displays a window that contains every referenced object that supports Click.
You then narrow the search by clicking the object or project that contains the Click you wanted.
This lesson described some theory behind VB objects and collections. Objects are more than variables in VB. Although this hour's lesson didn't go into a lot of depth about objects, you're now better prepared to program with objects and to learn more about them when you're ready.
In addition to collections, Visual Basic allows you to declare control arrays, which often act like object arrays. You can replicate controls on a form so that all the controls share common features, leaving you the task of changing only the distinguishing features such as captions or colors.
The system objects provide common predefined objects through which your application can interact with resources outside the typical program environment. By accessing the App object, your application at runtime can determine the path from which users started the application. The Clipboard object lets your application interact with the Windows Clipboard by copying and pasting text to and from the Clipboard area.
To organize things, VB supplies a tool called the Object Browser, which is basically a repository of data. You can search for specific events, properties, and methods, or can look for a whole class of objects. The Object Browser even tracks your code for objects you initialize and event procedures you write.
In Hour 21, "Accessing Files," you'll learn about file I/O and see how VB interacts with file data.
With chkMaster .Caption = "Primary Source" .Alignment = vbLeftJustify End With