Command BarEvents Events

Name Parameters Description

Click CommandBarControl Triggered when a hooked command bar button is clicked.

As Object, handled The CommandBarControl is passed to the event.

As Boolean, Cancel

Default As Boolean A single control can be hooked by many CommandBarEvents objects. The events are fired in reverse order of setting up (most recently set up fires first). An event handler can set the handled flag to True to tell subsequent handlers that the event has already been processed.

The CommandBarEvents object can also be used to hook into built-in menu items. If you want to handle the event through code, you can set the CancelDefault flag to True to stop the menu's normal action.

To demonstrate the use of CommandBarEvents, in a class module called CBarEvents, add the following code:

Public WithEvents oCBEvents As VBIDE.CommandBarEvents 'Hook into the Click event for the menu item

Private Sub oCBEvents_Click(ByVal CommandBarControl As Object, _ handled As Boolean, CancelDefault As Boolean)

Debug.Print "Clicked " & CommandBarControl.Caption End Sub

In a normal module, add the following code:

'Declare a collection to hold all the instances of our events class Dim ocolMenus As New Collection

Sub AddMenus()

'Declare some CommandBar items Dim oBar As CommandBar

Dim oBtnl As CommandBarButton, oBtn2 As CommandBarButton

'And an object to hold instances of your events class Dim oCBE As CBarEvents

'Get the VBE's menu bar

Set oBar = Application.VBE.CommandBars("Menu Bar") 'Add a menu item to it

Set oBtnl = oBar.Controls.Add(Type:=msoControlButton, temporary:=True) oBtnl.Caption = "Menul" oBtnl.Style = msoButtonCaption

'Create a new instance of your CommandBarEvent handler Set oCBE = New CBarEvents

'Link your CommandBarEvent handler to the menu item you just created Set oCBE.oCBEvents = Application.VBE.Events.CommandBarEvents(oBtnl)

'And add the instance of your event handler to the collection ocolMenus.Add oCBE

'Repeat for a second menu

Set oBtn2 = oBar.Controls.Add(Type:=msoControlButton, temporary:=True) oBtn2.Caption = "Menu2" oBtn2.Style = msoButtonCaption

Set oCBE = New CBarEvents

Set oCBE.oCBEvents = Application.VBE.Events.CommandBarEvents(oBtn2) ocolMenus.Add oCBE End Sub

When you run the AddMenus routine, two menus are added to the VBE standard menu bar, which both use your CommandBarEvents handling class to hook into their Click event. When you click each of the menu items, the Immediate window displays the menu's caption.

0 0

Post a comment