Share via


Working with the Document Object

You can reference a Document object as a member of the Documents collection by using either its index value (where 1 is the first document in the collection) or its name. In addition, you can use the ActiveDocument property to return a reference to the document that currently has the focus. For example, if a document named Policies.doc is the only open document, the following three object variables will all point to Policies.doc:

Dim docOne      As Word.Document
Dim docTwo      As Word.Document
Dim docThree    As Word.Document

Set docOne = Documents(1)
Set docTwo = Documents("Policies.doc")
Set docThree = ActiveDocument

You will rarely refer to a document by using its index value in the Documents collection because this value can change for a given document as other documents are opened and closed. Typically, you will use the ActiveDocument property or a Document object variable created by using the Documents collection's Add method or Open method. The following example shows how you can use the ActiveDocument property to add an address to the document that currently has the focus:

Sub AddOPGAddress()
   With ActiveDocument
      .Envelope.Insert Address:="The MOD Team" _
         & vbCrLf & "One Microsoft Way" & vbCrLf _
         & "Redmond, WA 98052", ReturnAddress:= _
         "One Happy Customer" & vbCrLf & _
         "77 Pine Bough Lane" & vbCrLf & _
         "Any Town, USA 12345"
   End With
End Sub

The next example illustrates how to create an instance of a Document object variable by using the Documents collection's Open method. After the Document object variable is set, the code calls the procedure from the prior example to add an envelope and then the envelope and the document are printed. Finally, the document is closed and all changes are saved.

Dim docPolicy As Word.Document

Set docPolicy = Documents.Open("c:\my documents\policies.doc")
With docPolicy
   Call AddOPGAddress
   .Envelope.PrintOut
   .PrintOut
   .Close SaveChanges:=True
End With

Note   The document opened by using the Open method or the document created by using the Add method will also be the currently active document represented by the ActiveDocument property. If you want to make some other document the active document, use the Document object's Activate method.

See Also

Working with Microsoft Word Objects | The Document Object | Opening, Creating, Saving, and Closing New Documents