How to close-without-save an Excel /xlsm workbook, w/ a custom function, from C#
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.
Jack Huang
Updated on August 23, 2020Comments
-
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 over 8 yearsIs it truly necessary to pass the
System.Reflection.Missing.Value
arguments to theClose
method? I'm closing by only passing false, and haven't had any problems yet. -
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 over 8 yearsIt is no longer necessary to pass the
Missing.Value
. With support for named and optional arguments introduced in C# 4.0, you can just writexlWorkBook.Close(SaveChanges: false);
-
John about 8 yearsWhat 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 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 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 about 8 years@John Specify file name
-
John about 8 yearsAhh!!! My mistake. I don't want to overwrite. Instead add the new data to existing file (Keeping the old data safe)
-
Motomotes about 8 years@John You need to ask a new question, please.