在公共模块中,写入下面函数:
Function CreateShortcutMenu() '创建快捷菜单,win7 64位的电脑,需引用 c:\windows\syswow64\fm20.dll
Dim cmb As Object 'CommandBar
Dim ctl As Object 'CommandBarButton
On Error Resume Next
CommandBars("ShortcutMenu").Delete
Set cmb = CommandBars.Add("ShortcutMenu", 5) 'msoBarPopup
Set ctl = cmb.Controls.Add(1) 'msoControlButton
ctl.Caption = "事件1"
ctl.FaceID = 3177 '设置按钮的图标,可以不要
ctl.OnAction = "=Actions1()"
Set ctl = cmb.Controls.Add(1) 'msoControlButton
ctl.Caption = "事件2"
ctl.FaceID = 3178 '设置按钮的图标,可以不要
ctl.OnAction = "=Actions2()"
End Function
Function Actions1()
MsgBox "这是事件1,其它代码自己添加!"
End Function
Function Actions2()
MsgBox "这是事件2,其它代码自己添加!"
End Function
然后在需要使用自定义右键菜单的窗体中,写入下面代码:
Private Sub Form_Load()
CreateShortcutMenu '调用模块中的函数,创建右键菜单
Dim ctl As Control
For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Or ctl.ControlType = acListBox Then
ctl.ShortcutMenuBar = "ShortcutMenu" '给所有文本框,组合框,列表框添加右键自定义菜单
End If
Next
End Sub
然后保存并运行窗体,就可以了.