How to: Programmatically Close Workbooks

How to: Programmatically Close Workbooks

 

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

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

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

To close the active workbook in a document-level customization

  1. Call the Close method to close the workbook associated with the customization. To use the following code example, run it in the Sheet1 class in a document-level project for Excel.

                Globals.ThisWorkbook.Close(false);
    

To close the active workbook in a VSTO Add-in

  1. Call the Close method to close the active workbook. To use the following code example, run it in the ThisAddIn class in an VSTO Add-in project for Excel.

                this.Application.ActiveWorkbook.Close(false, missing, missing);
    

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

To close a workbook that you specify by name

  1. Specify the workbook name as an argument to the Workbooks collection. The following code example assumes that a workbook named NewWorkbook is open in Excel.

                object fileName = "NewWorkbook.xlsx";
                Excel.Workbook workbook = this.Application.Workbooks.get_Item(fileName);
                workbook.Close(false);
    

Working with Workbooks
How to: Programmatically Save Workbooks
How to: Programmatically Open Workbooks
Programmatic Limitations of Host Items and Host Controls
Optional Parameters in Office Solutions
Host Items and Host Controls Overview

Show:
© 2016 Microsoft