Partager via


How to: Programmatically close documents

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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.

Close the active document

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.

    Note

    This example passes the wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

    Me.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
    
    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 Close method of the ActiveDocument property to close the active document. To use the following code example, run it from the ThisAddIn class in your project.

    Note

    This example passes the wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

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

Close a document that you specify by name

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 Documents collection, and then call the Close method. The following code example assumes that a document named NewDocument is open in Word.

    Note

    This example passes the wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

    Application.Documents("NewDocument.docx").Close(Word.WdSaveOptions.wdDoNotSaveChanges)
    
    Word._Document doc = Application.Documents["NewDocument.docx"] as Word._Document;
    doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
    

See also