How to close-without-save an Excel /xlsm workbook, w/ a custom function, from C#

39,780

When you use the Excel objects, be sure to close the workbook like this:

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add("Yourworkbook");

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

....do your stuff

xlWorkBook.Close(false, misValue, misValue);

xlApp.Quit();

The false in the close method indicates don't save changes.

Share:
39,780
Jack Huang
Author by

Jack Huang

Updated on August 23, 2020

Comments

  • Jack Huang
    Jack Huang almost 4 years

    I have an Excel workbook with a custom non-time-dependent cell function that I am opening from a C# WindowsForms application using Interop.Excel. I read four values from it, perform no explicit changes/calculations, then close it from C#.

    When I try to directly close (without saving), I get a save prompt. I suspect this is because Excel is interpreting auto-recalculation on open as creating a change, even though nothing actually numerically or formulaically changes. I also set Excel.Application.Calculation = Excel.XlCalculation.xlCalculationManual. How do I prevent the save prompt from appearing and just close-without-save?

  • Jeremy Cook
    Jeremy Cook over 8 years
    Is it truly necessary to pass the System.Reflection.Missing.Value arguments to the Close method? I'm closing by only passing false, and haven't had any problems yet.
  • Motomotes
    Motomotes over 8 years
    @JeremyCook Once upon a time it was, maybe the need to do so changed with a dot net update.
  • Ronald Boehm
    Ronald Boehm over 8 years
    It is no longer necessary to pass the Missing.Value. With support for named and optional arguments introduced in C# 4.0, you can just write xlWorkBook.Close(SaveChanges: false);
  • John
    John about 8 years
    What if I want to close the worksheet after saving it ? I don't want SaveAs dialog to be displayed as well. Force save kind of thing ?
  • Motomotes
    Motomotes about 8 years
    @John Really a different question, but do something like this before xlWorkBook.Close : Application.DisplayAlerts = False xlWorkBook.SaveAs (etc.) Application.DisplayAlerts = True
  • John
    John about 8 years
    @Motes This saves multiple copies... My workbook is referenced and edited a number times. Is it possible to overwrite the existing one ?
  • Motomotes
    Motomotes about 8 years
    @John Specify file name
  • John
    John about 8 years
    Ahh!!! My mistake. I don't want to overwrite. Instead add the new data to existing file (Keeping the old data safe)
  • Motomotes
    Motomotes about 8 years
    @John You need to ask a new question, please.