开发者

Ignore excel vba errors during read cell values from C# through COM interop

开发者 https://www.devze.com 2023-01-10 14:26 出处:网络
I am running VBA macros from C# which can yield errors. These errors are characterized by a pop-up prompting for debugging, interrupting the application and requiring user input. I need these macros a

I am running VBA macros from C# which can yield errors. These errors are characterized by a pop-up prompting for debugging, interrupting the application and requiring user input. I need these macros and they c开发者_开发百科annot be disabled.

How I can ignore these errors or close dialogs automatically?


Ör in the most simplest easiest way. Include on error resume next in your macros,so that the macro wont stop at errors.


To hide the visual basic editor (which shows when a error occurs) before attempting to open the file, change the Excel.VBE.MainWindow.Visible to false. Be aware that if the debugger is not shown, you will have to catch an exception in your code, so, envelope your code with an try catch.

If macros are not needed and can be ignored, use the msoAutomationSecurityForceDisable to disable them completely.

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

精彩评论

暂无评论...
验证码 换一张
取 消