代码之家  ›  专栏  ›  技术社区  ›  Jon Fournier

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

  •  10
  • Jon Fournier  · 技术社区  · 17 年前

    我正在尝试使用VBA创建Excel的新实例,方法是:

    Set XlApp = New Excel.Application

    问题是,这个新的Excel实例没有加载我正常打开Excel时加载的所有加载项…Excel应用程序对象中是否有任何内容可用于加载所有用户指定的加载项?

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

    4 回复  |  直到 11 年前
        1
  •  24
  •   Jon Fournier    16 年前

    我再次研究了这个问题,以及application.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
    
        2
  •  5
  •   Mike Rosenblum    17 年前

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

    您必须使用 Application.Addins.Add(string fileName) 方法。

        3
  •  2
  •   Ben Brandt    12 年前

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

    有点背景…在我的公司中,我们有一个第三方Web应用程序,它使用JavaScript启动Excel并动态生成电子表格。我们还有一个Excel加载项,它覆盖了“保存”按钮的行为。外接程序为您提供了在本地或在线文档管理系统中保存文件的选项。

    在升级到Windows7和Office2010之后,我们发现电子表格生成Web应用程序出现问题。当Javascript在Excel中生成电子表格时,保存按钮突然失效。您将单击“保存”,但什么也没有发生。

    使用这里的其他答案,我可以用JavaScript构建一个解决方案。本质上,我们将在内存中创建Excel应用程序对象,然后重新加载特定的外接程序以恢复保存按钮的行为。以下是修复程序的简化版本:

    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) { }
    }
    
        4
  •  -1
  •   Siddharth Rout    13 年前

    尝试:

    Set XlApp = CreateObject("Excel.Application")

    推荐文章