31

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?

Jack Huang
  • 531
  • 1
  • 5
  • 12
  • 2
    you can also do a `workbook.Saved = true` before saving to let excel app know that this is already saved and no need to prompt.. – nawfal Jul 17 '12 at 14:22

1 Answers1

62

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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Motomotes
  • 4,111
  • 1
  • 25
  • 24
  • 1
    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. – Jeremy Cook Jan 22 '16 at 15:37
  • 1
    @JeremyCook Once upon a time it was, maybe the need to do so changed with a dot net update. – Motomotes Jan 22 '16 at 20:24
  • 3
    It is no longer necessary to pass the `Missing.Value`. With support for [named and optional arguments](https://msdn.microsoft.com/en-us/library/dd264739.aspx) introduced in C# 4.0, you can just write `xlWorkBook.Close(SaveChanges: false);` – Ronald Boehm Jan 24 '16 at 18:48
  • 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 ? – John Apr 12 '16 at 15:22
  • 2
    @John Really a different question, but do something like this before `xlWorkBook.Close` : `Application.DisplayAlerts = False` `xlWorkBook.SaveAs (etc.)` `Application.DisplayAlerts = True` – Motomotes Apr 12 '16 at 16:19
  • @Motes This saves multiple copies... My workbook is referenced and edited a number times. Is it possible to overwrite the existing one ? – John Apr 12 '16 at 16:58
  • 1
    @John Specify file name – Motomotes Apr 12 '16 at 17:01
  • Ahh!!! My mistake. I don't want to overwrite. Instead add the new data to existing file (Keeping the old data safe) – John Apr 12 '16 at 17:16
  • @John You need to ask a new question, please. – Motomotes Apr 12 '16 at 17:30