以编程方式实例化Excel时加载插件

时间:2008-10-17 18:48:22

标签: excel excel-vba excel-addins vba

我正在尝试使用VBA创建一个新的Excel实例:

Set XlApp = New Excel.Application

问题是这个新的Excel实例没有加载我正常打开Excel时加载的所有插件... Excel Application对象中是否有任何内容可以加载所有用户指定的插件?

我不是要加载特定的加载项,而是让新的Excel应用程序表现得像用户自己打开它一样,所以我真的在寻找所有用户选择的加载项的列表通常在打开Excel时加载。

4 个答案:

答案 0 :(得分:24)

我再次查看了这个问题,Application.Addins集合似乎在Tools-> Addins菜单中列出了所有插件,其中一个布尔值表明是否安装了插件。所以现在看来​​对我有用的是遍历所有插件,如果.Installed = true,那么我将.Installed设置为False并返回True,这似乎正确加载我的插件。

Function ReloadXLAddins(TheXLApp As Excel.Application) As Boolean

    Dim CurrAddin As Excel.AddIn

    For Each CurrAddin In TheXLApp.AddIns
        If CurrAddin.Installed Then
            CurrAddin.Installed = False
            CurrAddin.Installed = True
        End If
    Next CurrAddin

End Function

答案 1 :(得分:5)

不幸的是,使用CreateObject("Excel.Application")与使用New Excel.Application的结果相同。

您必须按文件路径&amp ;;单独加载所需的Addins。使用Application.Addins.Add(string fileName)方法命名。

答案 2 :(得分:2)

我将这个答案留给其他遇到此问题但使用JavaScript的人。

一点背景......在我的公司,我们有一个第三方网络应用程序,它使用JavaScript来启动Excel并动态生成电子表格。我们还有一个Excel加载项,它会覆盖“保存”按钮的行为。该加载项使您可以选择在本地或在我们的在线文档管理系统中保存文件。

我们升级到Windows 7和Office 2010后,发现我们的电子表格生成网络应用程序存在问题。当JavaScript在Excel中生成电子表格时,突然“保存”按钮不再起作用。你会点击保存而没有任何事情发生。

使用其他答案,我能够用JavaScript构建解决方案。基本上我们会在内存中创建Excel Application对象,然后重新加载特定的加载项以恢复我们的保存按钮行为。这是我们修复的简化版本:

function GenerateSpreadsheet()
{
    var ExcelApp = getExcel();
    if (ExcelApp == null){ return; }

    reloadAddIn(ExcelApp);

    ExcelApp.WorkBooks.Add;
    ExcelApp.Visible = true;
    sheet = ExcelApp.ActiveSheet;

    var now = new Date();
    ExcelApp.Cells(1,1).value = 'This is an auto-generated spreadsheet, created using Javascript and ActiveX in Internet Explorer';

    ExcelApp.ActiveSheet.Columns("A:IV").EntireColumn.AutoFit; 
    ExcelApp.ActiveSheet.Rows("1:65536").EntireRow.AutoFit;
    ExcelApp.ActiveSheet.Range("A1").Select;

    ExcelApp = null;
}

function getExcel() {
   try {
       return new ActiveXObject("Excel.Application");
   } catch(e) {
       alert("Unable to open Excel. Please check your security settings.");
       return null;
   }
}

function reloadAddIn(ExcelApp) {
    // Fixes problem with save button not working in Excel,
    // by reloading the add-in responsible for the custom save button behavior
    try {
        ExcelApp.AddIns2.Item("AddInName").Installed = false;
        ExcelApp.AddIns2.Item("AddInName").Installed = true;
    } catch (e) { }
}

答案 3 :(得分:-1)

尝试:

Set XlApp = CreateObject("Excel.Application")