2

我通过 C# 程序和 OLE 刷新 Excel 2007 数据连接。大部分工作由单个 Workbooks.RefreshAll() 语句完成。

就像刷新电子表格的本质一样,各种事情都可能出错。在刷新过程中,程序可以给出关于“无法从文件'|'中读取数据”的对话框错误消息,以及关于“重叠的透视表报告”的消息。这两个都是致命的,我应该能够捕捉到这些错误,并以错误退出我的程序。

不幸的是,我似乎无法捕捉到这些问题,相反,我的自动化程序一直处于等待状态,直到我出现并在对话框中按 Enter 键。

有谁知道是否可以以编程方式捕获 excel 对话框中显示的错误,而不是将它们显示给用户?

4

1 回答 1

9

Your best bet is to set the Application.DisplayAlerts property to False. That is, assuming that your Excel.Application object variable is named "xlApp", all you'd have to do is the following:

xlApp.DisplayAlerts = false;

Note that this will cause the default response to be taken for each dialog box, which is normally what you would want. (There's no good way around this. Leaving DisplayAlerts = True and using SendKeys might be your only other option, but would be ugly and very error prone.)

Since you are making this call via OLE Automation, this call is cross-process, and, therefore, the DisplayAlerts setting will persist until you change it. (If called in-process, via VBA, it is switches back to to true automatically when the routine completes. The same behavior probably applies for a VB.NET or C# add-in called via a CommandBar or Ribbon control, but one would need to test to be certain.)

于 2008-10-07T21:10:52.177 回答