Closing Excel application with Excel Interop without save message

Yonatan Nir picture Yonatan Nir · Nov 14, 2013 · Viewed 17k times · Source

I am working with Excel Interop COM object. I am writing a method in which I am opening and closing an Excel application followed by opening an Excel workbook and sheet. After I'm done working on them I am closing both the application and workbook. My problem is that this method can be called repeatedly several times and when the sheet and app are closing I get from the Excel application a message if I want to save the changes I've made. The method get stuck until I press "No" but I can't tell the user to press it every time.

How can I close the application without receiving this message or at least answer it by code?

These are the methods I'm using to close the application and workbook:

private void FreeWorkSheetResources(Excel.Worksheet sheet)
{
  Marshal.ReleaseComObject(sheet);
  sheet = null;
}

private void FreeWorkBookResources()
{
  if (_excelSheets != null)
  {
    Marshal.ReleaseComObject(_excelSheets);
    _excelSheets = null;
  }
  _excelWorkBook.Close();
  Marshal.ReleaseComObject(_excelWorkBook);
  _excelWorkBook = null;
}

private void FreeApplicationResources()
{
  _app.Quit();
  Marshal.ReleaseComObject(_app);
  _app = null;
  GC.Collect();
}

And this is the way I'm using them:

if (_app == null)
  {
    _app = new Excel.Application();
  }
  if (_excelWorkBook == null)
  {
    _excelWorkBook = GetWorkBook(_filePath);
  }
  ....
  ....
  FreeWorkBookResources();
  FreeApplicationResources();

Answer

Sudhakar Tillapudi picture Sudhakar Tillapudi · Nov 14, 2013

While Closing Your Excel WorkBook you can use following Statements:

object misValue = System.Reflection.Missing.Value;
xlWorkBook.Close(false, misValue, misValue);