5.1. Creating Object Model References

Before you can use the properties, methods, and events of an object model, you must first create a programmatic reference to the class containing the properties, methods, or events you wish to use. You do this by declaring a local object variable to hold a reference to the object. You then assign a reference to the object to the local variable. There are two methods, detailed next, for doing this in VB.

5.1.1. Generic Object References and Late Binding

In situations in which the object you are instantiating doesn't provide a type library, or when you are unsure at design time precisely which object you need to reference, you can use a local variable dimensioned as the generic type of Object. Then you use the CreateObject or GetObject function to return an object reference to assign to the local generic object variable. For example:

Dim oObjVar As Object
Set oObjVar = CreateObject("myComponent.myClass")

VB6 has also added to the functionality of the CreateObject function by allowing you to pass the server machine name as a string parameter. (For details on how to use CreateObject and GetObject see Chapter 7.)

Sidebar 1. If You Haven't Set It, You Can't Use It!

To assign an object reference to a local object variable, you must use the Set statement. The sole exception is the For Each...Next loop, which can iterate the object members of a collection. It generates an object reference automatically for each object that it iterates.

This ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.