今回はメニューの内容を動的に変更する方法を紹介します。
[標準モジュール]
Option Explicit
Private myRibbon As Office.IRibbonUI
Private flg As Boolean
Public Sub Ribbon_onLoad(ribbon As IRibbonUI)
Set myRibbon = ribbon
flg = True
End Sub
Public Sub button_onAction(control As IRibbonControl)
Select Case control.ID
Case "myButton"
flg = Not flg
myRibbon.Invalidate
Case Else
MsgBox control.ID
End Select
End Sub
Public Sub dynamicMenu_getContent(control As IRibbonControl, ByRef returnedVal)
Select Case flg
Case True
returnedVal = GetContent("myMenuButton", "Happy Button", "HappyFace", "button_onAction", 10)
Case False
returnedVal = GetContent("myMenuButton", "Sad Button", "SadFace", "button_onAction", 5)
End Select
End Sub
Public Sub dynamicMenu_getImage(control As IRibbonControl, ByRef returnedVal)
Select Case flg
Case True
returnedVal = "HappyFace"
Case False
returnedVal = "SadFace"
End Select
End Sub
Private Function GetContent(ByVal btnID As String, ByVal btnLabel As String, ByVal btnImageMso, ByVal btnOnAction As String, ByVal Count As Long) As String
Dim d As Object
Dim elmMenu As Object
Dim elmButton As Object
Dim i As Long
Set d = CreateObject("Msxml2.DOMDocument")
Set elmMenu = d.createElement("menu")
elmMenu.setAttribute "xmlns", "http://schemas.microsoft.com/office/2006/01/customui"
elmMenu.setAttribute "itemSize", "large"
For i = 1 To Count
Set elmButton = d.createElement("button")
With elmButton
.setAttribute "id", btnID & i
.setAttribute "label", btnLabel & i
.setAttribute "imageMso", btnImageMso
.setAttribute "onAction", btnOnAction
End With
elmMenu.appendChild elmButton
Set elmButton = Nothing
Next
d.appendChild elmMenu
GetContent = d.XML
Set elmMenu = Nothing
Set d = Nothing
End Function
※ リボンXMLの編集方法については「Office 2010対応Custom UI Editor Tool のインストール・使用方法」「Office Ribbon Editorの紹介」「SharpDevelopでリボンXMLを編集する」等のページを参照してください。
[リボンXML]
<?xml version="1.0" encoding="utf-8"?>
<customUI onLoad="Ribbon_onLoad" xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon>
<tabs>
<tab id="myTab" label="My Tab">
<group id="myGroup" label="My Group">
<button id="myButton" label="Change Menu" imageMso="FileCompactAndRepairDatabase" size="large" onAction="button_onAction" />
<dynamicMenu id="myDynamicMenu" label="My DynamicMenu" getImage="dynamicMenu_getImage" size="large" getContent="dynamicMenu_getContent" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
Sponsored Links
上記のように"dynamicMenu"要素の"getContent"属性のコールバック関数を使うことによって、メニューの内容を動的に変更することができます。
・ リボン上のメニューからテンプレートを選択する(Word)