使用Interop.Excel检查Excel文件是否包含VBAmacros

在我的应用程序中,我必须检查一个Excel文档是否包含vbmacros。 所以我写了下面的方法来检查excel文件:

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; } 

有了一些excel文件,我从excel中得到了一个运行时错误91的信息。

91:对象variables或未设置块variables

我debugging它,只是意识到消息出现在调用excelApplication.Workbooks.Close(); 。 如果我删除这行代码,但在excelApplication.Quit();的调用中出现相同的excel消息excelApplication.Quit();

我该如何正确closuresExcel表格并防止Excel显示此消息?

与您的任务相关,您可以参考以下改进的代码片段,它使用.NET / C#, Microsoft.Office.Interop.Excel对象库和Runtime.InteropServices.Marshal对象:

 internal static bool? ExcelContainsMacros(string pathToExcelFile) { bool? _hasMacro = null; Microsoft.Office.Interop.Excel._Application _appExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook _workbook = null; try { _workbook = _appExcel.Workbooks.Open(pathToExcelFile, Type.Missing, true); _hasMacro = _workbook.HasVBProject; // close Excel workbook and quit Excel app _workbook.Close(false, Type.Missing, Type.Missing); _appExcel.Application.Quit(); // optional _appExcel.Quit(); // release COM object from memory System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_appExcel); _appExcel = null; // optional: this Log function should be defined somewhere in your code LogHasMacros(hasMacros); return _hasMacro; } catch (Exception ex) { // optional: this Log function should be defined somewhere in your code LogError(ex); return null; } finally { if (_appExcel != null) { _appExcel.Quit(); // release COM object from memory System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_appExcel); } } 

通知可空 bool? 键入:在此上下文中,由函数返回的null指示错误(换句话说,结果是未确定的), true / false值表示在testing中的Excel文件中是否存在任何VBAmacros。

希望这可能有帮助。