透過 VBA 操作 CommandBars 集合,可在 Word 右鍵文字選單中加入自訂命令、建立子選單、禁用內建命令或快速鍵。以下提供三組完整程式碼範例。
Private Sub Document_Close()
On Error Resume Next
Application.CommandBars("Text").Controls("Test").Delete ' 還原選單
End Sub
Private Sub Document_Open()
Dim Half As Byte
On Error Resume Next
Dim NewButton As CommandBarButton
Application.CommandBars("Text").Controls("Test").Delete ' 預防性刪除
Half = Int(Application.CommandBars("Text").Controls.Count / 2) ' 中間位置
Set NewButton = Application.CommandBars("Text").Controls.Add(Type:=msoControlButton, Before:=Half)
With NewButton
.Caption = "Test"
.FaceId = 100
.Visible = True
.OnAction = "MySub"
End With
End Sub
Sub MySub()
MsgBox "It's A Test For CommandBars(""Text"")!", vbOKOnly + vbInformation
End Sub
Sub ComReset() ' 徹底重設右鍵選單
Application.CommandBars("Text").Reset
End Sub
Private Sub Document_Close()
On Error Resume Next
Application.CommandBars("Text").Controls("New Menu").Delete
End Sub
Private Sub Document_Open()
Dim i As Byte, Half As Byte, strName As String
Dim NewButton As CommandBarPopup, MenuAdd As CommandBarButton
On Error Resume Next
Application.CommandBars("Text").Controls("New Menu").Delete
Half = Int(Application.CommandBars("Text").Controls.Count / 2)
Set NewButton = Application.CommandBars("Text").Controls.Add(Type:=msoControlPopup, Before:=Half)
With NewButton
.Caption = "New Menu"
.Visible = True
End With
For i = 1 To 4
strName = "Menu" & i
Set MenuAdd = NewButton.Controls.Add(Type:=msoControlButton)
With MenuAdd
.Caption = strName
.OnAction = "MySub"
.State = msoButtonDown
.Visible = True
End With
Next
End Sub
Sub MySub()
Dim ActionCap As String
ActionCap = CommandBars.ActionControl.Caption
MsgBox ActionCap
' 可用 Select Case ActionCap 區分各命令執行不同程序
With Application.CommandBars("Text").Controls("New Menu")
If .Controls(ActionCap).State = msoButtonDown Then
MsgBox "It's A Test!", vbOKOnly + vbInformation
.Controls(ActionCap).State = msoButtonUp
Else
.Controls(ActionCap).State = msoButtonDown
End If
End With
End Sub
Sub ComReset()
Application.CommandBars("Text").Reset
End Sub
Sub Example()
' 將自訂儲存於作用中文件
Application.CustomizationContext = ActiveDocument
' 依標題定位按鈕(唯一)
Application.CommandBars("Standard").Controls("開啟舊檔(&O)...").Enabled = False
' 依索引定位(不直觀,易受位置變動影響)
Application.CommandBars("Standard").Controls(2).Enabled = True
' 依 ID 定位(唯一、可迴圈)
Application.CommandBars.FindControl(ID:=23).Enabled = True
' 依索引組合定位
Application.CommandBars(1).Controls(2).Enabled = False
End Sub
Sub FileOpen() ' 可同時禁用命令與快速鍵
MsgBox "這是修改 WORD 命令/開啟檔案"
End Sub
Sub Sample() ' 將 Ctrl+O 重新指派給巨集
CustomizationContext = ActiveDocument
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyO), _
KeyCategory:=wdKeyCategoryMacro, Command:="NoFileOpen"
End Sub
Sub NoFileOpen()
MsgBox "This is only a test!"
End Sub
以上範例展示了動態修改右鍵選單、工具列按鈕啟用狀態、快速鍵綁定的核心技巧,可直接套用於文件或樣板中。