如何在 VSTO 中添加现有的 Excel 加载项

问题描述

我正在开发 VSTO 插件。我不想在其中编写 UDF,尽管我知道如何按照 COM 内容或使用 ExcelDNA 编写它。相反,我只想包含现有的 xlam 加载项之一,其中包含大量 UDF。因此,当人们安装 VSTO 插件时,我也希望安装 xlam 插件。所以我在 ThisAddin_startup 事件中编写了这段代码

        bool isExist=false;
        foreach (Excel.AddIn a in Application.AddIns)
        {                
            if (a.Name=="foobar.xlam") 
            {      
                if (!a.Installed)
                    a.Installed = true;
                isExist = true;
                break;
            }                
        }

        if (isExist==false)    
           this.Application.AddIns.Add(pathtotheaddin).Installed = true; //it is inside the resources folder
    

但我不断收到“AddIns 类的添加方法失败”错误。我做错了什么?

解决方法

我终于找到了。这是因为还没有打开的工作簿,所以它不能安装任何加载项。您知道,当还没有打开工作簿时,加载项按钮将被禁用。