MS-Word / General Formatting

Of Objects, Properties, and Methods

VBA is inherently object oriented, which means that it deals extensively with programming elements known as objects. Simply put (as though that's possible), an object is a named entity that represents a component of a Word document. For example, a Document object represents an entire Word document, whereas a Selection object represents the text that's selected in a document.

Objects have three components:

  • Property: Defines the data associated with an object. For example, the Selection object has a Text property that contains the text in the selection.
  • Method: Defines actions that the object can perform. For example, the Selection object has a Copy method that copies the selection to the Clipboard.
  • Event: Defines actions that an object can respond to. For example, when the user closes a document, the Document object raises a Close event.

Then you can write a macro routine that is executed to add special processing for the Close event.

Although events can be important in certain types of macros, most macros work with just the properties and methods of various Word objects.

Using objects

The basic trick for working with objects in VBA is that you use the period to separate the name of the object you want to work with from the name of the property or method you want to use. For example, Selection.Text refers to the Text property of the Selection object, and Range.Copy refers to the Copy method of the Range object.

One of the most important points about object-oriented programming is that the properties of an object can themselves be other objects that have properties and methods. For example, the Selection object has a Font property, which is itself a Font object. The Font object, in turn, has its own properties, such as Name and Size. So, you can refer to the Name property of the selection's font like this: Selection.Font.Name.

Another key to understanding objects is knowing that you can create variables to refer to them. You specify the type of a variable with the As keyword. For example, the following line declares a variable named f that represents a Font object:

Dim f As Font

Then you can assign an object to the variable.

You can't use the normal assignment statement to assign objects, however. Instead, you must use a Set statement, like this:

Set f As Selection.Font

In this line, the Font variable f is set to the object referred to by the Font property of the Selection object.

You can then refer to properties of the object variable in the usual way. For example, f.Name refers to the Name property of the f object.

[Previous] [Contents] [Next]