Call Excel Macro from Ribbon Button

心已入冬 提交于 2020-06-02 03:40:50

问题


I have a VBA Macro that works perfect in excel via a button, but i want to include a button in the excel ribbon(which i have done) but i do not know how to connect the ribbon button to the macro correctly, here is my C# and XML code:

C#

public class Ribbon1 : Office.IRibbonExtensibility
{
    private Office.IRibbonUI ribbon;

    TimeSpan startTimeSpan = new TimeSpan(0, 0, 5, 0);

    TimeSpan timeDecrease = TimeSpan.FromSeconds(1);

    private Timer timer = new Timer();

    public void Ribbon_Load(Office.IRibbonUI ribbonUI)
    {
        timer.Interval = 1000;
        this.ribbon = ribbonUI;
        timer.Tick += timer_Tick;
        timer.Start();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        if (startTimeSpan.ToString() != "00:00:00")
        {
            startTimeSpan = startTimeSpan - timeDecrease;
            ribbon.InvalidateControl("timerLabel");
        }
        else
        {
            startTimeSpan = new TimeSpan(0, 0, 5, 0);
            return;
        }
    }

    public string timerLabel_getLabel(Office.IRibbonControl control)
    {
        return startTimeSpan.ToString();
    }

    private void button1_onAction(Office.IRibbonControl control)
    {
        Globals.ThisWorkbook.Application.Run("'PM MailMerge.xlsm'!MailMerge.MailMerge");
    }

XML

<?xml version="1.0" encoding="UTF-8"?>
<customUI onLoad="Ribbon_Load" xmlns="http://schemas.microsoft.com/office/2009/07/customui" >
<ribbon>
<tabs>
  <tab  id="TimerTest" 
        label="Practice Monitoring">
    <group  id="group1" 
            label="MailMerge">
      <labelControl id="timerLabel" 
                     getLabel="timerLabel_getLabel"/>
      <button   id="button1" 
                label="Merge" 
                size="large" 
                onAction="'PM MailMerge.xlsm'!MailMerge.MailMerge"/>
    </group>
  </tab>
</tabs>
</ribbon>
</customUI>

回答1:


This will run the macro from the current opened excel workbook or macro from the workbook available in xlstart(C:\Users\\AppData\Roaming\Microsoft\Excel\XLSTART) folder

 Globals.ThisWorkbook.Application.Run("Your macroname")


来源:https://stackoverflow.com/questions/21428977/call-excel-macro-from-ribbon-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!