在从C#到COM互操作的读取单元格值期间忽略excel vba错误

Ron*_*881 6 c# excel vba com-interop excel-vba

我正在从C#运行VBA宏,这可能会产生错误.这些错误的特点是弹出提示进行调试,中断应用程序并要求用户输入.我需要这些宏,他们不能被禁用.

如何自动忽略这些错误或关闭对话框?

Ale*_*ela 0

要在尝试打开文件之前隐藏 Visual Basic 编辑器(发生错误时显示),请将 Excel.VBE.MainWindow.Visible 更改为 false。请注意,如果未显示调试器,您将必须捕获代码中的异常,因此,请使用 try catch 封装您的代码。

如果不需要宏并且可以忽略宏,请使用 msoAutomationSecurityForceDisable 完全禁用它们。

using InteropExcel = Microsoft.Office.Interop.Excel;

var Excel = new InteropExcel.Application ();

// Excel window will NOT popup if macro errors are found but
// exceptions might be raised when you execute the broken
// macro.
Excel.VBE.MainWindow.Visible = false;

// Uncomment to disable macros completely.
// Excel.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;

// I used this snippet to open a file with a broken macro.
var MyWorkbook = Excel.Workbooks.Open (@"YourFilePath");
var FirstWorksheet = (InteropExcel.Worksheet)MyWorkbook.Worksheets ["Plan1"];
var MyCell = ((InteropExcel.Range)FirstWorksheet.Cells [1,1]);
var CellValue = (Int32)MyCell.Value;
Run Code Online (Sandbox Code Playgroud)