【问题标题】:Identify which ribbon control was clicked from a macro (MS Word VBA)确定从宏中单击了哪个功能区控件 (MS Word VBA)
【发布时间】:2016-02-17 01:23:04
【问题描述】:

我有几个宏都做几乎相同的事情:每个都打开一个单独的文件。我通过自定义功能区上的控件激活它们。但不是有几个看起来像这样的宏:

ChangeFileOpenDirectory SeriesPath
Documents.Open FileName:="Doc1.docx", _
    ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
    PasswordDocument:=Password$, PasswordTemplate:="", Revert:=False, _
    WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
    wdOpenFormatAuto, XMLTransform:=""

但是只更改了文件名,我希望有一个宏可以打开任何一个文档,具体取决于单击了哪个功能区元素。问题是,我需要知道被点击的功能区元素的 ID。我浏览过几个网站都建议使用 IRibbonUI.ID 属性,但是当我尝试这样做时,我从 Word 中收到一条错误消息:“运行时错误 91:对象变量或未设置块变量。”

这是我的功能区的导出 XML 代码示例:

<mso:button idQ="x1:Open_00_1_549FAC6" label="00" imageMso="BlackAndWhiteDontShow" onAction="Open_00" visible="true"/>
<mso:button idQ="x1:Open_01_10_549FAC6" label="01" imageMso="AppointmentColor0" onAction="Open_01" visible="true"/>
<mso:button idQ="x1:Open_02_9_549FAC6" label="02" imageMso="AppointmentColor1" onAction="Open_02" visible="true"/>
<mso:button idQ="x1:Open_03_8_549FAC6" label="03" imageMso="AppointmentColor2" onAction="Open_03" visible="true"/>

有谁知道我做错了什么?

【问题讨论】:

标签: vba ms-word ribbon


【解决方案1】:

首先,请原谅任何语法错误,这些答案在伪 vba/xml 中。

1) 我建议使用功能区控件对象的 id 参数来确定被调用者,而不是使用不同的函数。您可以将它们重命名为更干净的名称,例如:

idQ="x1:Open_00" label="00" ... onAction="Open_OnAction"
idQ="x1:Open_01" label="01" ... onAction="Open_OnAction"

2) 然后您可以根据 ID 进行“解析”,或者只对整个 ID 执行 case/switch 语句

Sub Open_OnAction(control As IRibbonControl)
    Dim filename As String
    Select Case control.id
        Case "x1:Open_00"
            filename = "somefilename00.xml"
        Case "x1:Open_01"
            filename = "somefilename01.xml"
    End Select

    'The rest of your code here
End Sub

*注意:如果你想更流畅,你可以将文件名放入 ID(通过 XML),甚至不使用 case 语句,然后将其解析出来。例如:

idQ="Open_myfilenamepathhere" ... onAction="Open_OnAction"

Sub Open_OnAction(control As IRibbonControl)
    Dim filename As String

    'This splits the control into multiple array elements based on delimeter of "_", then grabs the 2nd element (since the array's first element is 0)
    filename = Split(control.id,"_")(1)

    'The rest of your code here
End Sub

【讨论】:

  • 这就是我在尝试定义 IRibbonControl 时收到错误“对象变量或未设置块变量”的原因。如果我尝试从功能区将参数传递给子,我会得到“参数不是可选的”。
猜你喜欢
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 2010-12-16
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多