The VBA and VB6 Add-In Object Models (VBIDE) expose a CommandBarEvents
object that have a Click
event, and the event signature is:
Dim WithEvents CmdBarEvents As CommandBarEvents Private Sub CmdBarEvents_Click(ByVal CommandBarControl As Object, handled As Boolean, CancelDefault As Boolean)
And a reference to a CommandBarControl
is passed to VBE.Events.CommandBarEvents
to register the event handler for that CommaneBarControl
:
Set CmdBarEvents = Application.VBE.Events.CommandBarEvents(CmdBarItem)
The Office object model defines individual CommandBar controls that have their own Click
events, for example, the CommandBarControl
object which has a Click
event, and the signature is:
Dim WithEvents CmdBarBtn As CommandBarButton Private Sub CmdBarBtn_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean)
And a reference to a CommandBarButton
is assigned to the WithEvents
object:
Set CmdBarButton = myButton
Why is there a difference, and which should I prefer?
I'm attaching events to the controls on the VBE's CommandBars (as opposed to CommandBars within the host application).
Office CommandBars don't have access to a CommandBarEvents
object, so I assume that they must use the CommandBarButton.Click
event. But the VBE (under any Office Host) has access to CommandBarButton
events AND CommandBarEvents
events, so I could use either approach, although the mere presence of the CommandBarEvents
object suggests that it is the preferred method (and probably the only method in non-Office VBA hosts), and most of the online examples of adding event handlers to VBE CommandBars do use CommandBarEvents
.
Carlos Quintero of MZ Tools has wonderously useful, but in this case, mildly contradictory information on his site. He suggests that The CommandBarEvents approach was used in the old Microsoft Visual Basic 5.0 / 6.0 environment, but also uses the CommandBarControl.Click
approach on this page
Is there something special about the VBE and attaching events to CommandBar
controls? Are there any problems (memory leaks, IDTExtensibility2 shutdown problems and the like) if I choose to use the CommandBarControl
events over the CommandBarEvents
events?