As you are opening the workbook the best advice is to keep track of the workbook and close it when appropriate. If your code is quite detailed then you could store a Boolean
value indicating whether the file is currently open or closed.
In Excel there is no property such as IsOpen. You could try to reference the workbook:
Workbook wbTest = xlApp.Workbooks.get_Item("some.xlsx");
but this creates a COM error if the book is not open, so gets quite messy.
Instead, create your own function IsOpen
that returns a boolean and loops through the currently open workbooks (the Workbooks
collection) checking the name, using code like this:
foreach (_Workbook wb in xlApp.Workbooks)
{
Console.WriteLine(wb.Name);
}
workbook.Close()
would not be necessary if the workbook has been saved - reflecting the normal behaviour of Excel. However, all Excel object references need to be released. As you have discovered, this is a little fiddly, and Close
and Quit
do not achieve this on their own.
static bool IsOpen(string book)
{
foreach (_Workbook wb in xlApp.Workbooks)
{
if (wb.Name.Contains(book))
{
return true;
}
}
return false;
}