The Object Data Type

A variable that contains a reference to an object within Microsoft Excel or within some other application can be declared with the Object data type. You can assign an object variable (using the Set statement) to represent any actual object recognized by the application.


Dim wk As Object
Set wk = Worksheets(1)

Object variables are initialized to the special value Nothing. You can test for this value using the Is function.


If wk Is Nothing Then    'object variable not set

Whenever possible, declare data as the most specific object type possible. For example, declare a variable that will represent a collection of ovals as Ovals instead of DrawingObjects; or, in the preceding code , declare the variable that will represent a worksheet as Worksheet instead of Object. Visual Basic can resolve references to the properties and methods of objects with specific types before you run the application (properties and methods for objects declared with the Object type must be resolved at run time; this slows down your macro). Specific object types are listed in the Object Browser.

When working with objects contained in other applications, instead of using the Variant type or the generic Object type, declare objects as they're listed in the Objects/Modules box in the Object Browser. This ensures that Visual Basic recognizes the specific type of object you're referencing, allowing the reference to be resolved at compile time.

For more information about creating and assigning objects and object variables, see Chapter 4, "Objects and Collections."