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

时间:2016-03-29 13:48:40

标签: c# excel excel-vba office-interop excel-interop vba

在我的应用程序中,我必须检查excel文档是否包含vb-macros。所以我编写了以下方法来检查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:对象变量或未设置块变量

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

如何正确关闭Excel工作表并防止Excel显示此消息,我该怎么做?

1 个答案:

答案 0 :(得分:3)

与您的任务相关,您可以参考以下精炼代码段,该代码段使用.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值表示正在测试的Excel文件中是否存在任何VBA宏。

希望这可能会有所帮助。