在 VB.Net/VSTO 中捕获 VBA 错误

Catch VBA Errors in VB.Net/VSTO

我在这个网站和其他网站上搜索了这些问题的答案,还搜索了我在 VB/VSTO 上的 VB/C# 本书合集。到目前为止,我画了一个空白。我已经 post 在 VB.NET facebook 小组中提出了同样的问题,如果我得到了解决方案,我会 post 在这里,这样它会帮助其他人。

我正在使用 VB.Net 和 VSTO 为 Excel 开发应用程序级插件。

部分功能涉及打开 .xlsm(Excel 启用宏)文件。 我有三个问题希望你能帮我解答。

  1. 我想打开每个启用宏的 xlsm 文件,但不启动 xlsm 文件中的任何 Auto_Open 宏,或触发 Workbook_Open 事件。这可能吗?

  2. xlsm 文件可能有自己的功能区附加到文件。是吗 可以禁止添加 xlsm 的功能区吗?

  3. xlsm 文件可能包含连接到 VBA 的 ActiveX 控件 宏。如果 VBA 宏产生错误,是否可以捕获 .NET 加载项中的错误?该错误可能包括“宏不 找到

有关信息,目前我使用下面的代码片段禁用宏。虽然这对项目 #1 有帮助,但对项目 #2 或 #3 没有帮助(事实上,禁用宏是项目 #3 的原因)。

目前,当我打开 xlsm 文件时,我使用以下代码禁用了宏:

' WorkbookType is a string representing a keyword within the Excel filename

        ' xlApp is running instance of Excel
        Dim xlApp = Marshal.GetActiveObject("Excel.Application")
        aWorkbook = xlApp.ActiveWorkbook
        aSheet = xlApp.ActiveSheet

        ' Save current macro security setting
        Dim oldSecurity = xlApp.AutomationSecurity

        ' Disable macros
        xlApp.AutomationSecurity = 
        Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable

        ' Find & open WorkbookType workbook files in ProjectFolder
        Dim info As New DirectoryInfo(CurrentProjectFolder)
        For Each fileItem As IO.FileInfo In info.GetFiles
                If fileItem.Name.Contains("~") Then
                ' Ignore temporary files
                ElseIf fileItem.Name.Contains(WorkbookType) AndAlso fileItem.Name.Contains(".xls")             Then
                        xlApp.AskToUpdateLinks = False
                        Dim wb = xlApp.Workbooks.Open(CurrentProjectFolder & "\" & fileItem.Name, UpdateLinks:=False)
                        xlApp.AskToUpdateLinks = True
                End If
        Next

        ' Restore macro security setting
        xlApp.AutomationSecurity = oldSecurity

The xlsm file may have ActiveX controls that are connected to VBA macros. If a VBA macro produces an error, is it possible to catch the error in the .NET Add-In? The error may include "macro not found"

COM add-ins(由 VSTO add-ins 表示)和 VBA 宏是完全不同的实体。您无法处理 COM add-ins 中的 VBA 错误,或者相反。但是您可能会对应用程序事件做出反应,请参阅 Object model (Excel) 以获取可用事件列表。

The xlsm file may have it's own ribbon attached to the file. Is it possible to inhibit the xlsm's ribbon from being added?

要防止自定义功能区 UI 加载,您需要通过删除 Excel 文件中包含的功能区 XML 自定义项来编辑文件。 VBA 现在不提供任何 UI 定制。您可以使用 Open XML SDK 从 VSTO add-ins 即时编辑打开的 XML 文档,而无需涉及主机应用程序或其对象模型。