VBA 直接访问功能区元素值

VBA direct access to ribbon element values

如何访问我的自定义功能区元素?

元素是在 (.xlsm\customUI\customUI.xml)

<ribbon startFromScratch="false">
    <tabs>
        <tab idMso="TabHome">
            <group id="MatrixGroup" label="xxx" insertBeforeMso="GroupClipboard">
                <button id="b1" label="111" imageMso="DataFormSource" onAction="asas" />
                <button id="b2" label="222" imageMso="ConditionalFormattingClearMenu" onAction="sasa" />
                <dropDown id="Drop" label=" Env" sizeString="WWWWWWWWW">
                    <item id="Item1" label="1"/>
                    <item id="Item2" label="2"/>
                    <item id="Item3" label="3"/>            
                    <item id="Item4" label="4"/>
                </dropDown>
            </group>
        </tab>
    </tabs>
</ribbon>

当我点击按钮 id="b1" 时,我需要选择 dropDown 元素 name/id 所以 dropDown 元素的 onAction="myMacro" 在这里无济于事。

但无论如何,有一个代码可以获取下拉元素 ID - 也许您可以将其转换为从另一个 Sub 调用此 Sub(通过按下按钮 id="b1" 触发)

Sub GetS(control As IRibbonControl, id As String, index As Integer)
    If control.id = "Drop" Then
    MsgBox id
End If End Sub

在这种情况下您可能会使用几个回调:

  1. GetSelectedItemIndex:我认为这是returns Selected Item from Dropdown 控件的索引位置。
  2. GetItemLabel: Returns 从功能区下拉控件中选择的项目标签
  3. GetItemID:Returns指定Index项的ID

每个人的签名是:

Sub GetSelectedItemIndex(control As IRibbonControl, ByRef returnedVal)

End Sub

Sub GetItemLabel(control As IRibbonControl, Index As Integer, ByRef returnedVal)

End Sub

Sub GetItemID(control As IRibbonControl, Index As Integer, ByRef id)

End Sub

你说得对,你可以将 control 对象从一个回调传递到另一个回调(本质上是手动 invoking/triggering 这些回调过程)。

我无法对此进行测试,所以我会根据记忆和猜测进行一些操作,您可能需要自行调整和调试,但希望这对您有所帮助。如果我没记错的话,这需要工作的方式是调用 sasa 回调时,您需要手动调用 GetSelectedItemIndex 然后 GetItemLabel,传递适当的 control对象。

这是棘手的部分,保持 dropDown control 对象的句柄。

实际上,Ribbon 对象有一些困难,我发现通过将它最初加载到自定义 class 对象(保留对每个控件的直接对象引用a Dictionary 属性,由控件键入 name/id),以便我可以随意从其他程序传递它们)。这个 here 有一些背景知识可能足以继续,就设置 Class 对象而言,您只需要添加另一个 属性 GetLet 过程作为 Dictionary 类型,因此您可以将每个功能区控件添加到字典中。如果您在实施时遇到问题,请单独提出一个问题,我会尽力提供帮助。

因此,一旦您可以访问适当的控件,就将该对象传递给 GetSelectedItemIndex 例如:

Dim ctrl as IRibbonControl
Dim itm_id, itm_index 
Set ctrl = {some object reference to the dropDown control}

Call GetSelectedItemIndex(ctrl, itm_index)
Call GetItemId(ctrl, itm_index, itm_id)
MsgBox(itm_id)