In my application I have to check if a excel-document contains vb-macros. So I've written the following method to check the excel-document:
internal static bool ExcelContainsMacros(string pathToExcelFile)
{
bool hasMacros = true;
Microsoft.Office.Interop.Excel._Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbooks = null;
try
{
object isReadonly = true;
workbooks = excelApplication.Workbooks.Open(
pathToExcelFile, missing, isReadonly, missing, missing, missing,
missing, missing, missing, missing, missing, missing,
missing, missing, missing);
hasMacros = workbooks.HasVBProject;
LogHasMacros(hasMacros);
}
catch (Exception exception)
{
LogError(exception);
}
finally
{
excelApplication.Workbooks.Close();
excelApplication.Quit();
}
return hasMacros;
}
With some excel-files I get a message from excel with a runtime-error 91.
91: Object variable or With block variable not set
I debugged it and just realized that the message appears at the call to excelApplication.Workbooks.Close();
. If I remove this line of code but the same excel-message appears at the call of excelApplication.Quit();
.
What do I have to do to close the excel-sheet correctly and prevent excel from showing this message?