O'Reilly logo

VB & VBA in a Nutshell: The Language by Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.8. Object Variables and Binding

Although Object variables are in many ways no different from other types of variables, the fact that they are references to other software components rather than simple values warrants special attention. While objects, classes, and binding are discussed in greater depth in Chapter 4, a short introduction to the subject is nevertheless worthwhile.

3.8.1. Declaring Object Variables

Object variables are declared in much the same way as other variables. There are three ways to declare an object variable:

Dim myObject As LibName.ClassName
Dim myObject As New LibName.ClassName
Dim myObject As Object

In each of the methods shown above, a Private or Public statement can replace the Dim statement, and the same scope rules apply as for other variables.

In the first declaration, the object variable is referenced to the class type library, but no instance of the class is assigned to the variable. At this stage, myObject is set to Nothing. To reference the class in this manner, you must have used the References dialog to add a reference to the class to your project. To assign a reference to a real instance of the class, you must use the Set statement prior to using the variable; for example:

Set myObject = LibName.ClassName

This produces an early bound reference to the object.

In the second declaration, a reference to a new instance of the class is assigned to the object variable, which is now ready to use immediately. Again, to reference the class in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required