Visual Basic Concepts

Dependent Objects

Sometimes there is a clear relationship between two objects, such that one object is a part of the other. In Microsoft Excel, for example, a Button object is always part of another object, such as a Worksheet.

An object that’s contained in another object is called a dependent object. Client applications can manipulate dependent objects, just as they can manipulate externally creatable objects, but they cannot create dependent objects using CreateObject or New.

Set the Instancing property of a class module to PublicNotCreatable to make the objects created from that class dependent objects.

Note*   Dependent objects are also referred to as *nested objects.

Getting References to Dependent Objects

If a client application can use dependent objects but can’t create them, how are they created?

A component can provide dependent objects in several ways. Most commonly an externally creatable object will have a collection with an Add method which the client can invoke. The component creates the dependent object in the code for the Add method, and returns a reference to the new object, which the client can then use.

For example, a Microsoft Excel Worksheet object has a collection of Button objects. A client application can add a new button to the worksheet by calling the Add method of the Buttons collection, as shown in the following code fragment:

' Note: The variable wsBudget contains a reference to
'   a Worksheet object.
Dim btnOK As Excel.Button
' Parameters of the Add method specify the top, left,
' width, and height of the new button. The return value
' is a reference to the new Button object.
Set btnOK = wsBudget.Buttons.Add(100, 100, 150, 125)
' Set the caption of the new Button object.
btnOK.Caption = "OK"

It’s important to remember that the variable btnOK contains a reference to the object, not the object itself.

Note   The distinction between externally creatable objects and dependent objects is made for the benefit of the client applications that manipulate a component’s objects. From within a component, you can always create objects from any of the component’s classes, regardless of the value of the Instancing property.

For More Information   "Combining Externally Creatable and Dependent Objects" discusses the process of identifying the types of objects needed for each part of an object model.