自定义菜单项可以在插件启动时候添加,即增加到ThisAddIn_Startup() 内。
下面以具体代码说明:
[代码7] 增加自定义菜单项
'插件启动时候
Private Sub ThisAddIn_Startup() Handles Me.Startup
……
Call addMenu()
End Sub
Private Sub addMenu()
'单元格右键时候的弹出菜单
Dim cMenuControl As Office.CommandBar = Globals.ThisAddIn.Application.CommandBars("Cell")
'增加菜单项到菜单第一个
Dim cButtonControl As Microsoft.Office.Core.CommandBarControl = cMenuControl.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Before:=1)
'转换为CommandBarButton
Dim cButton As Microsoft.Office.Core.CommandBarButton = CType(cButtonControl, Microsoft.Office.Core.CommandBarButton)
cButton.Caption = "查看菜单"
cButton.Tag = "这是自定义菜单项"
cButton.FaceId = 22
'增加菜单项按下事件
AddHandler cButton.Click, AddressOf menu_click
End Sub
以上代码运行后会在单元格右键菜单上增加一个“查看菜单”菜单项,位置在第一个。如下图所示:
图23 增加自定义菜单项
如果把代码中
Before:=1
修改为
Before:=5
那么菜单项将增加到第5个位置,如下图所示:
图24 自定义菜单项位置改变后
在实际中,以上代码会存在一定问题,读者可以测试,当运行多次后会发现多出很多相同的菜单项,也就是菜单项重复被添加。
修改后的代码如下:
Private Sub addMenu()
'单元格右键时候的弹出菜单
Dim cMenuControl As Office.CommandBar = Globals.ThisAddIn.Application.CommandBars("Cell")
'列出当前菜单的所有菜单项
For Each cControl As Microsoft.Office.Core.CommandBarControl In cMenuControl.Controls
'下面一句代码可以输出当前所有菜单项
'System.Diagnostics.Debug.WriteLine(cControl.Caption & " " & cControl.Id)
' 如果已经存在我们自定义的菜单项
If cControl.Caption = "查看菜单" Then
'1、可以退出
'Exit Sub
'2、可以将之前已经存在的菜单项删除
cControl.Delete()
End If
Next
'增加菜单项到菜单第一个
Dim cButtonControl As Microsoft.Office.Core.CommandBarControl = cMenuControl.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Before:=1)
'转换为CommandBarButton
Dim cButton As Microsoft.Office.Core.CommandBarButton = CType(cButtonControl, Microsoft.Office.Core.CommandBarButton)
cButton.Caption = "查看菜单"
cButton.Tag = "这是自定义菜单项"
cButton.FaceId = 22
'增加菜单项按下事件
AddHandler cButton.Click, AddressOf menu_click
End Sub
顺便将自定义菜单项的事件增加如下:
'菜单项按下事件:列出所有的命令栏ID和名称
Public Sub menu_click(ByVal control As Office.CommandBarButton, ByRef cancelDefault As Boolean)
'在Excel里面随时记住从1开始,而非vb中的0开始
Dim i As Integer = 1
Dim Wbook As Excel.Workbook = Application.Workbooks(1)
Dim Wsheet As Excel.Worksheet
Wsheet = Wbook.Worksheets("sheet1")
For Each cMenuControl As Office.CommandBar In Globals.ThisAddIn.Application.CommandBars
Wsheet.Cells(i, 1).Value = cMenuControl.Id
Wsheet.Cells(i, 2).Value = cMenuControl.Name
Select Case cMenuControl.Type
Case 0
Wsheet.Cells(i, 3).Value = "msoBarTypeNormal"
Case 1
Wsheet.Cells(i, 3).Value = "msoBarTypeMenuBar"
Case 2
Wsheet.Cells(i, 3).Value = "msoBarTypePopup"
Case Else
End Select
i += 1
Next
MsgBox("ok")
End Sub