When you open a book, the best advice is to keep track of the book and close it when necessary. If your code is sufficiently detailed, you can save a Boolean value indicating whether the file is currently open or closed.
Excel does not have a property like IsOpen. You can try to access the book:
Workbook wbTest = xlApp.Workbooks.get_Item("some.xlsx");
but this creates a COM error if the book is not open, so it becomes quite dirty.
Instead, create your own IsOpen function, which returns a boolean and will go through the current open books ( Workbooks collection), checking the name using the following code:
foreach (_Workbook wb in xlApp.Workbooks) { Console.WriteLine(wb.Name); }
workbook.Close() not required if the workbook is saved, which reflects the normal behavior of Excel. However, all references to Excel objects must be released. As you have discovered, this is a bit difficult, 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; }
source share