Export (0) Print
Expand All
Expand Minimize

How to: Reference Documents in the Documents Collection

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

You can refer to a Microsoft.Office.Interop.Word.Document object as a member of the Documents collection by using the name of the document or its index value in the collection.

Referring to a document by its name is usually the better choice if you want to work with a specific document. You 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.

Referencing Documents

To reference a document by its name

  • Set an object variable to point to the named document, SampleDoc.doc.

    NoteNote

    If you want to access data binding or the additional events added to a Microsoft.Office.Tools.Word.Document, you must declare the variable as the type Microsoft.Office.Tools.Word.Document.

    object fileName = "SampleDoc.doc"; 
    Word.Document doc = Application.Documents.get_Item(ref fileName); 
    
    

If you want to refer to the active document (the document that has focus), you can use the ActiveDocument property of the Application object. However, if you are only working with the document associated with your project, you can use the Me reference when you need to refer to the document that has the focus.

To reference the active document

  • Retrieve the name of the active document using ActiveDocument.

    string documentName = Application.ActiveDocument.Name;
    
    

To reference the document associated with the project

  • Retrieve the name of the document using ThisDocument.

    string documentName2 = Globals.ThisDocument.Name;
    
    

See Also

Community Additions

ADD
Show:
© 2014 Microsoft