用于从加载项执行功能的 Microsoft 功能区按钮

Microsoft Ribbon button to execute function from add-in

好的,所以我进行了大量的谷歌搜索,试图找到关于这个主题的信息,但我几乎一无所获。也许我没有为我要完成的工作寻找正确的术语。

我的问题是我在 MS Excel 加载项中编写了一个函数,我按照 Microsoft 的说明作为起点,但他们的教程让代码在用户每次保存时执行文件。我的目标是在我设计的功能区上有一个按钮执行此功能,而不是保存按钮。

这是我为了入门而遵循的 Microsoft 文章:https://msdn.microsoft.com/en-us/library/cc668205.aspx

我在这里也发现了这个问题,但它没有足够的细节让我弄清楚如何为自己实施解决方案:How to connect a ribbon button to a function defined in an Excel add-in?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace ExcelAddIn1
{
    public partial class ThisAddIn
    {
        void FormatTime(Microsoft.Office.Interop.Excel.Workbook WB, bool SaveAsUi, ref bool Cancel)
        {
            /////MY FUNCTION BODY HERE//////
        }
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

在此先感谢您的协助。

通常您可以使用Globals.ThisAddIn.Application访问应用程序级别和文档级别UI。 希望this link能帮到你。这是向工作表添加按钮的示例,如下所示:

Globals.Factory.GetVstoObject(
    Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1])
        .Controls.AddControl(button, selection, buttonName);

看起来像

VSTO 提供了两种创建自定义的方法UI:

  1. 功能区设计器 - 请参阅 Walkthrough: Creating a Custom Tab by Using the Ribbon Designer

  2. 原始 XML 标记 - Walkthrough: Creating a Custom Tab by Using Ribbon XML.

在这两种情况下,您都可以使用 Globals.ThisAddin 属性 访问加载项属性和方法,其中 returns 加载项 class 的一个实例(如图所示在上面列出的代码中)。