【问题标题】:Call Excel Macro from Ribbon Button从功能区按钮调用 Excel 宏
【发布时间】:2014-01-29 10:57:55
【问题描述】:

我有一个 VBA 宏,可以通过按钮在 excel 中完美运行,但我想在 excel 功能区中包含一个按钮(我已经完成),但我不知道如何将功能区按钮正确连接到宏,这是我的 C# 和 XML 代码:

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>

【问题讨论】:

    标签: c# xml excel vsto ribbon


    【解决方案1】:

    这将从当前打开的 Excel 工作簿中运行宏或从 xlstart(C:\Users\\AppData\Roaming\Microsoft\Excel\XLSTART) 文件夹中可用的工作簿中运行宏

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

    【讨论】:

    • 似乎无法让它工作,xlstart 文件夹在哪里?我没有使用 customUI 编辑器
    • 你的宏在哪里?它是否在您通过添加功能区控件进行自定义的同一文档中?
    • 只需传入你的宏名称作为参数
    • onAction="'PM MailMerge.xlsm'!MailMerge.MailMerge" 在 Ribbon.xml 必须是 onAction="button1_onAction"
    • 在 button1_onAction 方法上添加 try catch 并查找是否有任何异常。
    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多