Export (0) Print
Expand All
Expand Minimize
7 out of 13 rated this helpful - Rate this topic

How to: Save Workbooks

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 save a workbook using the Save method. If the workbook has not been saved before, you should call the SaveAs method instead, so you can specify a path. Without an explicit path, Microsoft Office Excel 2003 saves the file in the current folder with the name it was given when it was created. Use the SaveCopyAs method to save without modifying the open workbook in memory.

To save all open workbooks

  • Iterate through the Workbooks collection and call the Save method on each workbook.

    foreach (Excel.Workbook wkb in this.Application.Workbooks) 
    {
        wkb.Save();
    }
    
    

SaveAs Method

The SaveAs method is more complex than the Save method. This method allows you to save the specified workbook to a new location or with a new name, optionally specifying a file format, a password, an access mode, and more. Place the following code in the ThisWorkbook class:

To save the workbook in XML format

  • Save the workbook associated with the project to a specified location, saving in XML format:

    this.SaveAs(@"C:\Book1.xml", Excel.XlFileFormat.xlXMLSpreadsheet,
        missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlNoChange,
        missing, missing, missing, missing, missing);
    
    

You might want to set the DisplayAlerts property to False before calling the SaveAs method, because saving in some formats requires interaction. Setting this property to False causes Excel to use all defaults.

SaveCopyAs Method

The SaveCopyAs method saves a copy of the workbook to a file but does not modify the open workbook in memory. This method is useful when you want to create a backup copy without modifying the location of the workbook.

To save a backup copy of a workbook

  • Call the SaveCopyAs method of the workbook associated with the project:

    this.SaveCopyAs(@"C:\Book1.xls");
    
    

Compiling the Code

  • This code must be placed in the ThisWorkbook class, not in a sheet class.

Robust Programming

Interactively canceling any of the methods that save or copy the workbook raises a run-time error in your code. For example, if your procedure calls the SaveAs method but does not disable prompts from Excel, and your user clicks Cancel when prompted, Excel raises a run-time error.

See Also

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.