代码之家  ›  专栏  ›  技术社区  ›  User999999

通过代码禁用COM加载项

  •  0
  • User999999  · 技术社区  · 7 年前

    在我们公司内,有两个插件在Excel中无法相处。其中一个加载项来自SAP(例如,无法修改)。另一个是使用 Add In Express

    这个问题仅限于Excel。当我们试图从受保护的视图中提取文档时。使用以下代码

    ExcelApp.ActiveProtectedViewWindow.Edit()
    

    当我们执行这行代码时,另一个(SAP)插件开始抛出访问冲突。

    1st error: Attempted to read or write protected memory. This is often an indication that other memory is corrupt
    2nd error: Exception from HResult 0x800A03EC
    

    现在我正在努力解决冲突。但我被卡住了。 我找不到其他方法成功地将文档从受保护的视图中移出

    暂时禁用SAP加载项似乎效果不佳。因为 Application.Addins 不包含COM加载项。和 Application.CommAddins 引发以下错误:

           ExcelApp.COMAddIns   The embedded interop type 'COMAddIns' does not contain a 
           definition for'Microsoft.Office.Interop.Excel._Application' since it was not used 
           in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' 
           property to true.    
    

    然而 Embed Interop Types 设置为true。

    有人有什么想法吗?

    笔记 正在禁用 Protected view 不是选项。根据公司层面的决定:-(

    2 回复  |  直到 7 年前
        1
  •  0
  •   User999999    7 年前

    我已经设法解决了这个问题。感谢 Charles Williams 使用以下代码位,我可以使用vb禁用/启用某些COM加载项。密码

    这个 SapExcelAddIn 在这种情况下,就是导致我们所有问题的加载项。

    For Each certAddin As Object In ExcelApp.COMAddIns
          log("progId:" & certAddin.progId) 'Logging the id of all Com-addins
          If (certAddin.progId.Equals("SapExcelAddIn")) Then
               log("disconnecting:" & certAddin.progId)
               certAddin.Connect = False
          End If
    Next
    
        2
  •  0
  •   Colm Bhandal    3 年前

    为了防止有人想在C#中执行此操作,下面是一些代码,用于禁用多个COM加载项,这些加载项由名称通过数组参数指定:

    private void TryDisableCommAddIns(Microsoft.Office.Interop.Excel.Application app, string[] addInsToDisable)
            {
                if(addInsToDisable == null)
                {
                    return;
                }
                COMAddIns comAddIns = app.COMAddIns;
                foreach (string addInName in addInsToDisable)
                {
                    //If you have a logger you could log a debug statement such as: $"Disabling COM AddIn: {addInName}"
                    COMAddIn commAddInOrNull = GetCommAddInOrNull(comAddIns, addInName);
                    if(commAddInOrNull != null)
                    {
                        commAddInOrNull.Connect = false;
                    }
                }
            }
    
            private COMAddIn GetCommAddInOrNull(COMAddIns comAddIns, string addInName)
            {
                try
                {
                    return comAddIns.Item(addInName);
                }
                catch (Exception)
                {
                    //If you have a logger you could log a debug statement such as: $"No COM AddIn found with name: {addInName}"
                    return null;
                }
            }