How to: Programmatically Close Documents

How to: Programmatically Close Documents

 

You can close the active document or you can specify a document to close.

Applies to: The information in this topic applies to document-level projects and VSTO add-in projects for Word. For more information, see Features Available by Office Application and Project Type.

There are two procedures for closing the active document: one for document-level customizations and one for VSTO Add-ins.

To close the active document in a document-level customization

  1. Call the Close method of the ThisDocument class in your project to close the document associated with the customization. To use the following code example, run it from the ThisDocument class.

    System_CAPS_noteNote

    This example passes the F:Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; 
    this.Close(ref doNotSaveChanges, ref missing, ref missing);
    

To close the active document in a VSTO Add-in

  1. Call the M:Microsoft.Office.Interop.Word._Document.Close(System.Object@,System.Object@,System.Object@) method of the P:Microsoft.Office.Interop.Word._Application.ActiveDocument property to close the active document. To use the following code example, run it from the ThisAddIn class in your project.

    System_CAPS_noteNote

    This example passes the F:Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

    Word._Document document = this.Application.ActiveDocument;
    document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
    

The way that you close a document that you specify by name is the same for VSTO Add-ins and document-level customizations.

To close a document that you specify by name

  1. Specify the document name as an argument to the P:Microsoft.Office.Interop.Word._Application.Documents collection, and then call the M:Microsoft.Office.Interop.Word._Document.Close(System.Object@,System.Object@,System.Object@) method. The following code example assumes that a document named NewDocument is open in Word.

    System_CAPS_noteNote

    This example passes the F:Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

    Word._Document doc = Application.Documents["NewDocument.docx"] as Word._Document;
    doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
    
Show:
© 2016 Microsoft