Visual Basic Concepts

Creating Objects

The easiest way to create an object is to double-click a control in the Toolbox. However, to realize the full benefit of all the objects available in Visual Basic and from other applications, you can use Visual Basic's programmability features to create objects at run time.

  • You can create references to an object with object variables.

  • You can create your own objects "from scratch" with class modules.

  • You can create your own collections with the Collection object.

For More Information   Other chapters show you how to access objects. The CreateObject and GetObject functions, for example, are discussed in "Programming with Components."

Using Object Variables

In addition to storing values, a variable can refer to an object. You assign an object to a variable for the same reasons you assign any value to a variable:

  • Variable names are often shorter and easier to remember than the values they contain (or, in this case, the objects they refer to).

  • Variables can be changed to refer to other objects while your code is running.

  • Referring to a variable that contains an object is more efficient than repeatedly referring to the object itself.

Using an object variable is similar to using a conventional variable, but with one additional step — assigning an object to the variable:

  • First you declare it:

    Dim variable As class

  • Then you assign an object to it:

    Set variable = object

Declaring Object Variables

You declare an object variable in the same way you declare other variables, with Dim, ReDim, Static, Private, or Public. The only differences are the optional New keyword and the class argument; both of these are discussed later in this chapter. The syntax is:

{Dim | ReDim | Static | Private | Public} variableAs [New] class

For example, you can declare an object variable that refers to a form in the application called frmMain:

Dim FormVar As New frmMain   ' Declare an object
                           ' variable of type frmMain.

You can also declare an object variable that can refer to any form in the application:

Dim anyForm As Form         ' Generic form variable.

Similarly, you can declare an object variable that can refer to any text box in your application:

Dim anyText As TextBox      ' Can refer to any text box
                           ' (but only a text box).

You can also declare an object variable that can refer to a control of any type:

Dim anyControl As Control   ' Generic control variable.

Notice that you can declare a form variable that refers to a specific form in the application, but you cannot declare a control variable that refers to a particular control. You can declare a control variable that can refer to a specific type of control (such as TextBox or ListBox), but not to one particular control of that type (such as txtEntry or List1). However, you can assign a particular control to a variable of that type. For example, for a form with a list box called lstSample, you could write:

Dim objDemo As ListBox
Set objDemo = lstSample

Assigning Object Variables

You assign an object to an object variable with the Set statement:

Setvariable=object

Use the Set statement whenever you want an object variable to refer to an object.

Sometimes you may use object variables, and particularly control variables, simply to shorten the code you have to type. For example, you might write code like this:

If frmAccountDisplay!txtAccountBalance.Text < 0 Then
   frmAccountDisplay!txtAccountBalance.BackColor = 0   frmAccountDisplay!txtAccountBalance.ForeColor = 255
End If

You can shorten this code significantly if you use a control variable:

Dim Bal As TextBox
Set Bal = frmAccountDisplay!txtAccountBalance
If Bal.Text < 0 Then
   Bal.BackColor = 0
   Bal.ForeColor = 255
End If

Specific and Generic Object Types

Specific object variables must refer to one specific type of object or class. A specific form variable can refer to only one form in the application (though it can refer to one of many instances of that form). Similarly, a specific control variable can refer to only one particular type of control in your application, such as TextBox or ListBox. To see an example, open a new project and place a text box on a form. Add the following code to the form:

Private Sub Form_Click()
   Dim anyText As TextBox
   Set anyText = Text1
   anyText.Text = "Hello"
End Sub

Run the application, and click the form. The Text property of the text box will be changed to "Hello."

Generic object variables can refer to one of many specific types of objects. A generic form variable, for example, can refer to any form in an application; a generic control variable can refer to any control on any form in an application. To see an example, open a new project and place several frame, label, and command button controls on a form, in any order. Add the following code to the form:

Private Sub Form_Click()
   Dim anyControl As Control
   Set anyControl = Form1.Controls(3)
   anyControl.Caption = "Hello"
End Sub

Run the application, and click the form. The caption of the control you placed third in sequence on the form will be changed to "Hello."

There are four generic object types in Visual Basic:

Generic Object
Type

Object referenced
Form Any form in the application (including MDI children and the MDI form).
Control Any control in your application.
MDIForm The MDI form in the application (if your application has one).
Object Any object.

Generic object variables are useful when you don't know the specific type of object a variable will refer to at run time. For example, if you want to write code that can operate on any form in the application, you must use a generic form variable.

Note   Because there can be only one MDI form in the application, there is no need to use the generic MDIForm type. Instead, you can use the specific MDIForm type (MDIForm1, or whatever you specified for the Name property of the MDI form) whenever you need to declare a form variable that refers to the MDI form. In fact, because Visual Basic can resolve references to properties and methods of specific form types before you run your application, you should always use the specific MDIForm type.

The generic MDIForm type is provided only for completeness; should a future version of Visual Basic allow multiple MDI forms in a single application, it might become useful.

Forms as Objects

Forms are most often used to make up the interface of an application, but they're also objects that can be called by other modules in your application. Forms are closely related to class modules. The major difference between the two is that forms can be visible objects, whereas class modules have no visible interface.

Adding Custom Methods and Properties

You can add custom methods and properties to forms and access them from other modules in your application. To create a new method for a form, add a procedure declared using Public.

' Custom method on Form1
Public Sub LateJobsCount()
   .
. ' <statements>
   .
End Sub

You can call the LateJobsCount procedure from another module using this statement:

Form1.LateJobsCount

Creating a new property for a form can be as simple as declaring a public variable in the form module:

Public IDNumber As Integer

You can set and return the value of IDNumber on Form1 from another module using these two statements:

Form1.IDNumber = 3
Text1.Text = Form1.IDNumber

You can also use Property procedures to add custom properties to a form.

For More Information   Details on Property procedures are provided in "Programming with Objects."

Note   You can call a variable, a custom method, or set a custom property on a form without loading the form. This allows you to run code on a form without loading it into memory. Also, referencing a control without referencing one of its properties or methods does not load the form.

Using the New Keyword

Use the New keyword to create a new object as defined by its class. New can be used to create instances of forms, classes defined in class modules, and collections.

Using the New Keyword with Forms

Each form you create at design time is a class. The New keyword can be used to create new instances of that class. To see how this works, draw a command button and several other controls on a form. Set the form's Name property to Sample in the Properties window. Add the following code to your command button's Click event procedure:

Dim x As New Sample
x.Show

Run the application, and click the command button several times. Move the front-most form aside. Because a form is a class with a visible interface, you can see the additional copies. Each form has the same controls, in the same positions as on the form at design time.

Note   To make a form variable and an instance of the loaded form persist, use a Static or Public variable instead of a local variable.

You can also use New with the Set statement. Try the following code in a command button's Click event procedure:

Dim f As Form1
Set f = New Form1
f.Caption = "hello"
f.Show

Using New with the Set statement is faster and is the recommended method.

Using the New Keyword with Other Objects

The New keyword can be used to create collections and objects from the classes you define in class modules. To see how this works, try the following example.

This example demonstrates how the New keyword creates instances of a class. Open a new project, and draw a command button on Form1. From the Project menu, choose Add Class Module to add a class module to the project. Set the class module's Name property to ShowMe.

The following code in the Form1 module creates a new instance of the class ShowMe, and calls the procedure contained in the class module.

Public clsNew As ShowMe
Private Sub Command1_Click()
   Set clsNew = New ShowMe
   clsNew.ShowFrm
End Sub

The ShowFrm procedure in the class module creates a new instance of the class Form1, shows the form, and then minimizes it.

Sub ShowFrm()
   Dim frmNew As Form1
   Set frmNew = New Form1
   frmNew.Show
   frmNew.WindowState = 1
End Sub

To use the example, run the application, and click the command button several times. You'll see a minimized form icon appear on your desktop as each new instance of the ShowMe class is created.

For More Information   For information on using New to create objects, see "Programming with Components."

New Keyword Restrictions

The following table describes what you cannot do with the New keyword.

You can't use New to create Example of code not allowed
Variables of fundamental data types. Dim X As New Integer
A variable of any generic object type. Dim X As New Control
A variable of any specific control type. Dim X As New ListBox
A variable of any specific control. Dim X As New lstNames

Freeing References to Objects

Each object uses memory and system resources. It is good programming practice to release these resources when you are no longer using an object.

  • Use Unload to unload a form or control from memory.

  • Use Nothing to release resources used by an object variable. Assign Nothing to an object variable with the Set statement.

For More Information   See "Unload Event" and "Nothing" in the Language Reference.

Passing Objects to Procedures

You can pass objects to procedures in Visual Basic. In the following code example, it's assumed that there is a command button on a form:

Private Sub Command1_Click()
   ' Calls the Demo sub, and passes the form to it.
   Demo Form1
End Sub

Private Sub Demo(x As Form1)
   ' Centers the form on the screen.
   x.Left = (Screen.Width - x.Width) / 2
End Sub

It's also possible to pass an object to an argument by reference and then, inside the procedure, set the argument to a new object. To see how this works, open a project, and insert a second form. Place a picture box control on each form. The following table shows the property settings that need changes:

Object Property Setting
Picture box on Form2 Name
Picture
Picture2
c:\vb\icons\arrows\arw01dn.ico

The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it.

Private Sub Form_Click()
Form2.GetPicture Picture1
End Sub

The GetPicture procedure in Form2 assigns the Picture property of the picture box on Form2 to the empty picture box on Form1.

Private objX As PictureBox
Public Sub GetPicture(x As PictureBox)
   ' Assign the passed-in picture box to an object
   ' variable.
   Set objX = x
   ' Assign the value of the Picture property to Form1
   ' picture box.
   objX.Picture = picture2.Picture
End Sub

To use the example, run the application, and click Form1. You'll see the icon from Form2 appear in the picture box on Form1.

For More Information   The previous topics are intended to serve as an introduction to objects. To learn more, see "Programming with Objects" and "Programming with Components."