gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:50:30 25 4
gpt4 key购买 nike

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

我对其进行了调试,然后才意识到消息出现在对 excelApplication.Workbooks.Close(); 的调用中。如果我删除这行代码,但在调用 excelApplication.Quit(); 时会出现相同的 excel 消息。

我该怎么做才能正确关闭 excel 工作表并防止 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);
}
}

注意 nullable bool? 类型:在此上下文中,函数返回的 null 表示错误(换句话说,结果未确定), true/false 值表示被测 Excel 文件中是否存在任何 VBA 宏。

希望这可能有所帮助。

关于c# - 使用 Interop.Excel 检查 Excel 文件是否包含 VBA 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com