我想通过Word 2007中的VBA宏以编程方式显示右键单击上下文菜单。
这样我就可以将宏映射到热键,并在不离开键盘的情况下使用焦点显示菜单。我假设这将通过Application
对象的CommandBars
集合完成,可以按以下方式访问:
Application.CommandBars.'access appropriate mehod or member here'
但我没有看到任何方法或成员似乎会显示上下文菜单。是否可以通过VBA宏实现这一目标?
修改
根据建议,我遍历每个CommandBar并获取名称和索引以尝试找出要使用的CommandBar索引:
Sub C_RightClick()
'Activates right-click context menu
'
Dim cbar As Office.CommandBar
Dim cbarIndex As Integer
Dim testString As String
Dim cBarsArray(0 To 500)
Dim arrayCounter As Integer
testString = ""
arrayCounter = 1
For Each cbar In CommandBars
'TRUE if right-click
'If LCase(cbar.Name) = 'right-click' Then
' cbarIndex = cbar.Index
'End If
testString = testString + CStr(cbar.Index) + " " + cbar.Name + " " + CStr(cbar.Type = msoBarTypePopup) + vbCrLf
Debug.Print cbar.Name; " "; cbar.Type = msoBarTypePopup
'Add name to array and increment counter
cBarsArray(arrayCounter) = cbar.Name
arrayCounter = arrayCounter + 1
Next cbar
MsgBox testString
'Application.CommandBars(cbarIndex).ShowPopup
End Sub
但是,我没有看到任何标题为“右键单击”的内容。我认为它可能是'标准',其索引为1,但在我尝试访问它时收到错误。
如果有人知道选择Home
选项卡时Word 2007中显示的默认右键单击上下文菜单的正确名称,将不胜感激。否则,我会将这个问题提交给SuperUser并自行研究。谢谢你的帮助。
答案 0 :(得分:1)
尝试类似:
Application.CommandBars(100).ShowPopup
参数可以是Commandbar索引或标题。
要在命令栏上执行特定命令,请尝试以下操作:
Application.CommandBars(100).Controls("Paste").Execute
将所有命令栏列表打印到立即窗口:
Sub test()
Dim cbar As Office.CommandBar
For Each cbar In CommandBars
'TRUE if right-click
Debug.Print cbar.Name; " "; cbar.Type = msoBarTypePopup
Next cbar
End Sub
修改强> 在回答有关您通过HOME选项卡获得的右键单击菜单的问题时,我认为它是与CommandBar不同的控件。
为了更好地了解右键单击菜单名称和索引,我稍微修改了上面的代码。现在,这会尝试向每个右键单击菜单添加一个控件。添加的控件标题是菜单名称和索引。控件是临时的 - 下次打开Word时它们就会消失。
Sub test()
Dim cbar As Office.CommandBar
Dim ctl As Office.CommandBarControl
For Each cbar In Application.CommandBars
With cbar
On Error Resume Next
'this will delete any customizations
.Reset
Set ctl = .Controls.Add(Type:=msoControlButton, Temporary:=True)
ctl.Caption = .Index & " - " & cbar.Name
Debug.Print "Name: "; cbar.Name; " Right-click: "; cbar.Type = msoBarTypePopup; " Error descr: "; Err.Description
On Error GoTo 0
End With
Next cbar
End Sub
它还会将错误消息(如果有的话)打印到即时窗口。
我认为你不会对“Home”上下文菜单感到满意的原因是没有添加任何控件。这是添加了控件的菜单图片: