MS-Word / General Formatting

Using the With statement

The With statement is a special VBA shortcut that lets you refer to an object in several statements without having to refer to the object every time. You simply list the object in the With statement. Then any statement that appears between the With and its corresponding End With statement and that begins with a period uses the object listed in the With statement.

Suppose that you want to set the Bold and Italic properties of the Font property of the Selection object for a document named Temp. You can use these lines:

Documents("Temp").ActiveWindow.Selection.Font.Bold = True
Documents("Temp").ActiveWindow.Selection.Font.Italic = True

Or, you can place these lines within a With/End With block, like this:

With Documents("Temp").ActiveWindow.Selection.Font
    .Bold = True
    .Italic = True
End With

Granted, the With statement adds two lines of code. But if the object reference is complicated, it can save you some typing even if you need to set only two property values.

Working with collections

A collection is a special type of object that holds one or more occurrences of another object. The Word object model, which I discuss further in the next tutorial, has many collections that help organize the various objects used in Word. For example, you can store all open documents in a collection named Documents. And, you can access all paragraphs in a document via a collection named Paragraphs.

All collections have a Count property you can use to determine how many items are in the collection. For example, the following code displays the number of open documents:

MsgBox "There are currently " & Documents.Count _
    & " documents open."

Many collections have an Add method that adds a new item to the collection. In many cases, the Add method creates a new object of the type appropriate for the collection, adds it to the collection, and returns the new object as its return value. For example, the following chunk of code creates a new document and then displays the document's name:

Dim d As Document
Set d = Documents.Add
MsgBox "The new document's name is " & d.Name

You can access the individual items in a collection by using an index number. For example, the following code displays the name of the first document in the Documents collection:

MsgBox Documents(1).Name

In many cases, you can use the name of an item instead of an index. For example, this statement closes the document named TempDoc:

Documents("TempDoc").Close

If no document is named TempDoc, the statement generates an error.

[Previous] [Contents] [Next]