In some cases, you may want to provide access to your add-in through a menu command. In this example, we’ll place a menu command for our new add-in on the Tools menu.
The following procedure is designed to build on example code presented in “Creating a Basic Add-In.”
To place a menu command for an add-in on the Tools menu
Public VBI As VBIDE.VBE
' VBI is assigned a pointer to the current IDE's
' VBA object which is later passed as a parameter
' to the OnConnection procedure. It's retained
' because you need it later for disconnecting the
' add-in. Other procedures may have a need for it
' as well.
Private mcbMenuCommandBarCtrl As _
Office.CommandBarControl
' This will be set to the new command bar control.
Private WithEvents MenuHandler As CommandBarEvents
' This is the event handling procedure for
' the click event of the new command bar control.
Private Sub IDTExtensibility_OnConnection _
(ByVal VBInst As Object, _
ByVal ConnectMode As VBIDE.vbext_ConnectMode, _
ByVal AddInInst As VBIDE.AddIn, _
custom() As Variant)
' Save the current instance of Visual Basic.
Set VBI = VBInst
' Add a menu command to the Tools menu.
Set mcbMenuCommandBarCtrl = _
VBI.CommandBars("Tools").Controls.Add(before:=3)
' Place a separator bar before the new
' menu command.
mcbMenuCommandBarCtrl.BeginGroup = True
' Set the title for the add-in.
mcbMenuCommandBarCtrl.Caption = "My New Add-In"
' Copy an icon bitmap to the clipboard.
Clipboard.SetData _
LoadPicture("c:\windows\triangles.bmp")
' Copy the icon from the clipboard to the menu
' command's icon.
mcbMenuCommandBarCtrl.PasteFace
' Connect the event handler to receive the
' events for the new command bar control.
Set MenuHandler = _
VBI.Events.CommandBarEvents _
(mcbMenuCommandBarCtrl)
' Place a separator bar after the new
' menu command.
VBI.CommandBars("Tools").Controls(4).BeginGroup _
= True
End Sub
mcbMenuCommandBar.Delete
line ensures that the menu command in the Tools menu is removed once the add-in is disconnected. Add the following lines to the IDTExtensibility_OnDisconnection procedure. (You can also remove the MsgBox line from the original code if you wish):Private Sub IDTExtensibility_OnDisconnection _
(ByVal VBInst As Object, ByVal LoadMode As _
Long, ByVal AddInInst As VBIDE.AddIn, custom() _
As Variant)
' Delete the new menu command from the Tools
' menu.
mcbMenuCommandBarCtrl.Delete
End Sub
Private Sub MenuHandler_Click(ByVal _
CommandBarControl As Object, handled As Boolean, _
CancelDefault As Boolean)
MsgBox "You clicked the new menu command."
End Sub
To summarize, you now have an add-in which: