Commandbar in excel with vba

Содержание

  1. Метод CommandBars.Add (Office)
  2. Синтаксис
  3. Параметры
  4. См. также
  5. Поддержка и обратная связь
  6. Объект CommandBar (Office)
  7. Пример
  8. См. также
  9. Поддержка и обратная связь
  10. VBA Excel. Добавление кнопки в контекстное меню
  11. Свойство Application.CommandBars
  12. Добавление кнопки в контекстное меню
  13. Удаление кнопки из контекстного меню
  14. Примеры добавления и удаления кнопок
  15. Пример 1
  16. Объект CommandBars (Office)
  17. Пример
  18. См. также
  19. Поддержка и обратная связь
  20. Working With Commandbars
  21. EXISTING MENUS AND TOOLBARS
  22. Recommended Programs

Метод CommandBars.Add (Office)

Создает новую панель команд и добавляет ее в коллекцию панели команд.

Использование CommandBars в некоторых приложениях Microsoft Office было заменено новым компонентом ленты пользовательского интерфейса Microsoft Office Fluent. Дополнительные сведения см. в статье Обзор ленты Office Fluent.

Синтаксис

expression. Add (Name, Position, MenuBar, Temporary)

выражение (обязательно). Переменная, представляющая объект CommandBars .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Name Необязательно заполнять. Variant Имя новой панели команд. Если этот аргумент опущен, строке команд присваивается имя по умолчанию (например, Пользовательский 1).
Position Необязательный Variant Позиция или тип новой панели команд. Может быть одной из констант MsoBarPosition .
MenuBar Необязательный Variant Значение True , чтобы заменить активную строку меню новой строкой команд. Значение по умолчанию — False.
Temporary Необязательный Variant Значение true , чтобы сделать новую панель команд временной. Панели команд удаляются при закрытии приложения-контейнера. Значение по умолчанию — False.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Объект CommandBar (Office)

Представляет панель команд в приложении контейнера. Объект CommandBar является членом коллекции CommandBars .

Использование CommandBars в некоторых приложениях Microsoft Office было заменено новым компонентом ленты пользовательского интерфейса Microsoft Office Fluent. Дополнительные сведения см. в статье Обзор ленты Office Fluent.

Пример

Используйте CommandBars (index), где index — это имя или номер индекса панели команд, чтобы вернуть один объект CommandBar . В следующем примере показано, как пройти коллекцию панели команд, чтобы найти панель команд с именем Forms. Если он находит эту панель команд, пример делает ее видимой и защищает состояние закрепления. В этом примере переменная cb представляет объект CommandBar .

Используйте имя или номер индекса, чтобы указать строку меню или панель инструментов в списке доступных строк меню и панелей инструментов в приложении контейнера. Однако необходимо использовать имя, чтобы указать меню, контекстное меню или подменю (все из которых представлены объектами CommandBar ). В этом примере в нижней части меню Сервис добавляется новый элемент меню. При выборе нового пункта меню запускается процедура с именем «qtrReport».

Если два или более пользовательских меню или подменю имеют одинаковые имена, CommandBars(index) возвращает первое. Чтобы убедиться, что вы возвращаете правильное меню или подменю, найдите всплывающее меню, отображающее это меню. Затем примените свойство CommandBar к всплывающему элементу управления, чтобы вернуть панель команд, представляющую это меню. Если третий элемент управления на панели инструментов с именем Пользовательские инструменты является всплывающим элементом управления, в этом примере команда Сохранить добавляется в нижнюю часть этого меню.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Добавление кнопки в контекстное меню

Программное добавление кнопки в контекстное меню ячейки (строки, столбца) из кода VBA Excel. Свойство CommandBars объекта Application.

Свойство Application.CommandBars

Примеры командных панелей, вызываемых кликом правой кнопки мыши (контекстных меню):

  • CommandBars(«Cell») – контекстное меню ячейки;
  • CommandBars(«Row») – контекстное меню строки;
  • CommandBars(«Column») – контекстное меню столбца.

Добавление кнопки в контекстное меню

Добавление кнопки из кода VBA Excel в контекстное меню ячейки. Кнопки в контекстные меню строк и столбцов добавляются аналогично.

Если хотите создать постоянную кнопку для контекстного меню, используйте параметр Temporary метода Controls.Add в значении False , которое применяется по умолчанию:

Удаление кнопки из контекстного меню

Созданная предыдущим кодом VBA временная кнопка контекстного меню ячейки будет утилизирована только при закрытии приложения Microsoft Excel. Это означает, что если в приложении открыты несколько книг, тогда после закрытия книги с кодом, создавшим кнопку, она продолжит существование и будет доступна из других открытых книг. Если это не желательно, можно удалить кнопку следующей строкой:

Эта же строка удалит и постоянную кнопку.

Примеры добавления и удаления кнопок

Пример 1

Добавление кнопки в контекстное меню ячейки из кода VBA Excel при открытии книги и удаление кнопки при закрытии книги.

Добавление кнопки (код размещается в модуле книги):

Источник

Объект CommandBars (Office)

Коллекция объектов CommandBar , представляющих панели команд в контейнерном приложении.

Использование CommandBars в некоторых приложениях Microsoft Office было заменено новым компонентом ленты пользовательского интерфейса Microsoft Office Fluent. Дополнительные сведения см. в статье Обзор ленты Office Fluent.

Пример

Используйте свойство CommandBars , чтобы вернуть коллекцию CommandBars . В следующем примере в окне Интерпретация отображается имя и локальное имя каждой строки меню и панели инструментов, а также отображается значение, указывающее, отображается ли строка меню или панель инструментов.

Используйте метод Add , чтобы добавить новую панель команд в коллекцию. В следующем примере создается настраиваемая панель инструментов с именем Custom1 и она отображается в виде плавающей панели инструментов.

Используйте enumName, где index — это имя или номер индекса панели команд, чтобы вернуть один объект CommandBar . В следующем примере панель инструментов с именем Custom1 закреплена в нижней части окна приложения.

Используйте имя или номер индекса, чтобы указать строку меню или панель инструментов в списке доступных строк меню и панелей инструментов в контейнерном приложении. Однако имя необходимо использовать для указания меню, контекстного меню или подменю (все из которых представлены объектами CommandBar ). Если два или более настраиваемых меню или подменю имеют одинаковые имена, enumName возвращает первое. Чтобы убедиться, что вы возвращаете правильное меню или подменю, найдите всплывающее меню, отображающее это меню. Затем примените свойство CommandBar к всплывающему элементу управления, чтобы вернуть панель команд, представляющую это меню.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Working With Commandbars

By using toolbars and shortcut menus, you can provide quick access to commonly used commands. Excel has more than 50 different built-in toolbars and about 60 different shortcut menus, all of which are part of the

CommandBars collection. This collection also contains any new custom toolbars and menus you create. Due to their central location, you can easily make modifications to existing menus and toolbars, or add new ones as needed.

UNDERSTANDING THE COMMANDBARS COLLECTION

The CommandBars collection is part of the Application object, the main object that contains all Excel-related objects.

Each individual toolbar or menu is a separate CommandBar object. You can reference these objects either by an index value or by the object name. For example, the code CommandBars( «Standard» ) references the Standard toolbar. See Appendix A for a list of the built-in toolbars and shortcut menus in Excel.

EXISTING MENUS AND TOOLBARS

You can modify menus and toolbars either manually from Excel or you can create subroutines to modify these CommandBar objects. In Excel, you make modifications to toolbars and menus via the Customize command on the Tools menu. From the Customize menu you can add and remove both menu and toolbar options. See Chapter 1 for more information about adding macro references to toolbars and menus.

You can also write a procedure that modifies a particular menu or toolbar by adding or removing options. Each option on a toolbar or menu is a

CommandBarControl object associated with the corresponding CommandBar object. You reference the

CommandBarControls collection using the

Controls property. You add a new option to a toolbar or menu using the Add method.

When you call the Add method with the Controls object, you can apply the optional parameters of the method to specify the type of control to add. The following table describes each of the parameters you can call with the Add method to create a new control. After you add the control, you reference the CommandBarControl properties to set the specific properties for the individual control. See the sections «Add Controls to a Toolbar» and «Add Items to a Menu» for more information on adding options to toolbars and menus.

Was this article helpful?

Recommended Programs

Scheduler123 Excel-based Production Scheduling System

Mastering Excel Tables Course

Excel Advanced PivotTable Techniques Course

Источник

Adblock
detector

Excel determines which type of command bar a particular object contains by the value of the Type property. Excel has three types of command bar objects, as described in the following table.

Содержание

  • 1 Add a new commandbar
  • 2 Add ControlButton to CommandBar
  • 3 Adding a control to a command bar
  • 4 Add PopupControl to CommandBar
  • 5 Adjusting a control»s Visible property
  • 6 Attaching a drop-down list to a command bar
  • 7 Changing a control»s caption dynamically: Showing the user the current cell»s number format
  • 8 CommandBar Object
  • 9 CommandBars collection
  • 10 Counting custom toolbars
  • 11 Create Shortcut
  • 12 Creating a command bar: Set some properties when you create a new toolbar
  • 13 Creating a Toolbar: AddRemoveButton
  • 14 Creating a Toolbar and assign its action
  • 15 Creating a Toolbar and display MsgBox in its action
  • 16 Custom Toolbars
  • 17 deletes a control that has a caption of SortButton.
  • 18 Determines if a given command bar name exists
  • 19 Display Control Detail
  • 20 display shortcut menu with the ShowPopup method
  • 21 displays the Caption property for the first Control object contained in the Standard toolbar, whose index is 3.
  • 22 Finding Visible Controls with FindControls
  • 23 Get the type of CommandBars
  • 24 how your VBA code can change the position of a toolbar.
  • 25 Inspecting a CommandBar
  • 26 Listing all controls on all toolbars
  • 27 Listing the controls on a command bar
  • 28 Properties of CommandBar controls
  • 29 Rather than use an index number to refer to a control, you can use its Caption property setting
  • 30 Referring to command bars
  • 31 Removes a toolbar specified by the name passed in
  • 32 Removing all toolbars and then restoring them
  • 33 Replacing Excel»s built-in menu with your own
  • 34 Reset CommandBar
  • 35 Restores the Worksheet Menu Bar to its native state
  • 36 Restore tool bar
  • 37 Save list of all predefined commands and their ID numbers in a file
  • 38 Set Control style, Action, group, faceid and caption
  • 39 sets the FaceId property of the first button on the MyToolbar toolbar image to 45, which is the code number for a mailbox icon.
  • 40 Show All Toolbar Controls
  • 41 Show CommandBar Names
  • 42 show/hide check symbol
  • 43 Shows or hides a command bar.
  • 44 simply copies the NumberFormat property of the ActiveCell to the Caption property of the button control.
  • 45 The custom toolbar is removed with this procedure
  • 46 The Protection constants are additive: apply different types of protection with a single command
  • 47 The Protection property of a CommandBar object provides you with many options for protecting a CommandBar.
  • 48 This toolbar exists only when the cell pointer falls within a given range
  • 49 To delete a control from a CommandBar object, use the Delete method of the Controls collection
  • 50 Translates a MsoBarPosition enumeration into a text description of the bar position.
  • 51 Translates a MsoBarType enumeration into a text description of the bar type.
  • 52 Translates a MsoControlType enumeration into a text description of the control type.
  • 53 Working with Shortcut Menus

Add a new commandbar

   <source lang="vb">

Sub AddNewCB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  On Error GoTo AddNewCB_Err
  Set myCommandBar = CommandBars.Add(Name:="Sample Toolbar", Position:= msoBarFloating)
  myCommandBar.Visible = True
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .Caption = "Button"
     .Style = msoButtonCaption
     .TooltipText = "Display Message Box"
     .OnAction = "=MsgBox(""You pressed a toolbar button!"")"
  End With
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .FaceId = 1000
     .Caption = "Toggle Button"
     .TooltipText = "Toggle First Button"
     .OnAction = "=ToggleButton()"
  End With
  Set myCommandBarCtl = myCommandBar.Controls.Add(msoControlComboBox)
  With myCommandBarCtl
     .Caption = "Drop Down"
     .Width = 100
     .AddItem "Create Button", 1
     .AddItem "Remove Button", 2
     .DropDownWidth = 100
     .OnAction = "=AddRemoveButton()"
  End With
  Exit Sub

AddNewCB_Err:

  Debug.Print Err.number & vbCr & Err.Description
  Exit Sub

End Sub
Function ToggleButton()

  Dim CBButton As CommandBarControl
  On Error GoTo ToggleButton_Err
  Set CBButton = CommandBars("Sample Toolbar").Controls(1)
  CBButton.Visible = Not CBButton.Visible
  Exit Function
  

ToggleButton_Err:

  Debug.Print Err.number & vbCr & Err.Description
  Exit Function

End Function
Function AddRemoveButton()

  Dim myCommandBar As CommandBar, CBCombo As CommandBarComboBox
  Dim CBNewButton As CommandBarButton
  
  On Error GoTo AddRemoveButton_Err
  
  Set myCommandBar = CommandBars("Sample Toolbar")
  Set CBCombo = myCommandBar.Controls(3)
  
  Select Case CBCombo.ListIndex
     Case 1
        Set CBNewButton = myCommandBar.Controls.Add(Type:=msoControlButton)
        With CBNewButton
           .Caption = "New Button"
           .Style = msoButtonCaption
           .BeginGroup = True
           .Tag = "New Button"
           .OnAction = "=MsgBox(""This is a new button!"")"
        End With
     Case 2
        Set CBNewButton = myCommandBar.FindControl(Tag:="New Button")
        CBNewButton.Delete
  End Select
  Exit Function

AddRemoveButton_Err:

  If Err.number = 91 Then
     Debug.Print "Cannot remove button that does not exist!"
     Exit Function
  Else
     Debug.Print Err.number & vbCr & Err.Description
     Exit Function
  End If

End Function

</source>
   
  

Add ControlButton to CommandBar

   <source lang="vb">

Sub AddNewMB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  Dim myCommandBarSubCtl As CommandBarControl
  On Error GoTo AddNewMB_Err
  Set myCommandBar = CommandBars.Add(Name:="Sample Menu Bar", Position:= _
     msoBarTop, MenuBar:=True, Temporary:=False)
  myCommandBar.Visible = True
  myCommandBar.Protection = msoBarNoMove
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlPopup)
  myCommandBarCtl.Caption = "Displa&y"
  Set myCommandBarSubCtl = myCommandBarCtl.Controls.Add(Type:=msoControlButton)
  With myCommandBarSubCtl
     .Style = msoButtonIconAndCaption
     .Caption = "E&nable ClickMe"
     .FaceId = 59
     .OnAction = "=MsgBox(""You clicked Enable ClickMe"")"
     .Parameter = 1
     .BeginGroup = True
  End With
  Set myCommandBarSubCtl = myCommandBarCtl.Controls.Add(Type:=msoControlButton)
  With myCommandBarSubCtl
     .Style = msoButtonIconAndCaption
     .Caption = "Di&sable ClickMe"
     .FaceId = 276
     .OnAction = "=MsgBox(""You Disable ClickMe"")"
     .Parameter = 2
     .BeginGroup = True
  End With
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .BeginGroup = True
     .Caption = "&ClickMe"
     .Style = msoButtonCaption
     .OnAction = "=MsgBox(""You clicked ClickMe"")"
  End With
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .BeginGroup = True
     .Caption = "&Set Visibility Off"
     .Style = msoButtonCaption
     .OnAction = "=MsgBox(""You set visibility off"")"
  End With
  Exit Sub

AddNewMB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub

</source>
   
  

Adding a control to a command bar

   <source lang="vb">

Sub AddButton()

   Set NewBtn = CommandBars("MyToolbar").Controls.Add _
     (Type:=msoControlButton)
   With NewBtn
      .FaceId = 300
      .OnAction = "MyMacro"
      .Caption = "Tooltip goes here"
   End With

End Sub

</source>
   
  

Add PopupControl to CommandBar

   <source lang="vb">

Sub AddNewMB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  Dim myCommandBarSubCtl As CommandBarControl
  On Error GoTo AddNewMB_Err
  Set myCommandBar = CommandBars.Add(Name:="Sample Menu Bar", Position:= _
     msoBarTop, MenuBar:=True, Temporary:=False)
  myCommandBar.Visible = True
  myCommandBar.Protection = msoBarNoMove
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlPopup)
  myCommandBarCtl.Caption = "Displa&y"
  Set myCommandBarSubCtl = myCommandBarCtl.Controls.Add(Type:=msoControlButton)
  With myCommandBarSubCtl
     .Style = msoButtonIconAndCaption
     .Caption = "E&nable ClickMe"
     .FaceId = 59
     .OnAction = "=ToggleClickMe()"
     .Parameter = 1
     .BeginGroup = True
  End With

AddNewMB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub
Function ToggleClickMe()

  Dim MyMenu As CommandBar
  Dim myCommandBarClickMe As CommandBarControl
  On Error GoTo ToggleClickMe_Err
  Set MyMenu = CommandBars("Sample Menu Bar")
  Set myCommandBarClickMe = MyMenu.Controls(2)
  With CommandBars.ActionControl
     Select Case .Parameter
        Case 1
           myCommandBarClickMe.Enabled = True
        Case 2
           myCommandBarClickMe.Enabled = False
     End Select
  End With
  Exit Function

ToggleClickMe_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Function

End Function

</source>
   
  

Adjusting a control»s Visible property

   <source lang="vb">

Sub ToggleAllToolbars()

   For Each cb In CommandBars
       If cb.Type = msoBarTypeNormal Then
           cb.Visible = Not cb.Visible
       End If
   Next cb

End Sub

</source>
   
  

Attaching a drop-down list to a command bar

   <source lang="vb">

Sub Make()

   Dim TBar As commandBar
   Dim NewDD As CommandBarControl
   Set TBar = CommandBars.Add
   Set NewDD = CommandBars("myBar").Controls.Add(Type:=msoControlDropdown)
   With NewDD
       .Caption = "Date"
       .OnAction = "yourAction"
       .Style = msoButtonAutomatic
       For i = 1 To 2
           .AddItem "Click"
       Next i
       .ListIndex = 1
   End With

End Sub
Sub yourAction()

   With CommandBars("MonthList").Controls("DateDD")
       ActiveCell.value = .List(.ListIndex)
   End With

End Sub

</source>
   
  

Changing a control»s caption dynamically: Showing the user the current cell»s number format

   <source lang="vb">

Sub MakeNumberFormatDisplay()

   Dim TBar As CommandBar
   Dim NewBtn As CommandBarButton
   Set TBar = CommandBars.Add
   With TBar
       .Name = "Number Format"
       .Visible = True
   End With
   
   Set NewBtn = CommandBars("Number Format").Controls.Add(Type:=msoControlButton)
   With NewBtn
       .Caption = ""
       .OnAction = "ChangeNumFormat"
       .Style = msoButtonCaption
   End With

End Sub

</source>
   
  

CommandBar Object

   <source lang="vb">

Sub CommandBarCount()

  MsgBox "There are " & CommandBars.count & " command bars"

End Sub

</source>
   
  

CommandBars collection

   <source lang="vb">

Sub com()

   MsgBox CommandBars(1).Name

End Sub

</source>
   
  

Counting custom toolbars

   <source lang="vb">

Sub CustomToolbars()

   Dim cb As CommandBar
   For Each cb In CommandBars
       If cb.Type = msoBarTypeNormal Then
           If Not cb.BuiltIn Then
               Debug.Print "Not"
           End If
       End If
   Next cb

End Sub

</source>
   
  

Create Shortcut

   <source lang="vb">

Sub CreateShortcut()

   DeleteShortcut
   Set myBar = CommandBars.Add (Name:="MyShortcut", Position:=msoBarPopup, Temporary:=True)
   
   Set myItem = myBar.Controls.Add(Type:=msoControlButton)
   With myItem
       .Caption = "&Number Format..."
       .OnAction = "ShowFormatNumber"
       .FaceId = 1554
   End With
       
   Set myItem = myBar.Controls.Add(Type:=msoControlButton)
   With myItem
       .Caption = "&Alignment..."
       .OnAction = "ShowFormatAlignment"
       .FaceId = 217
   End With
       
   Set myItem = myBar.Controls.Add(Type:=msoControlButton)
   With myItem
       .Caption = "&Font..."
       .OnAction = "ShowFormatFont"
       .FaceId = 291
   End With

End Sub
Sub ShowFormatNumber()

   Application.Dialogs(xlDialogFormatNumber).Show

End Sub
Sub ShowFormatAlignment()

   Application.Dialogs(xlDialogAlignment).Show

End Sub
Sub ShowFormatFont()

   Application.Dialogs(xlDialogFormatFont).Show

End Sub

</source>
   
  

Creating a command bar: Set some properties when you create a new toolbar

   <source lang="vb">

Sub CreateAToolbar()

   Dim TBar As CommandBar
   Set TBar = CommandBars.Add
   With TBar
       .name = "MyToolbar"
       .Top = 0
       .Left = 0
       .Visible = True
   End With

End Sub

</source>
   
  

Creating a Toolbar: AddRemoveButton

   <source lang="vb">

Sub AddNewCB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  On Error GoTo AddNewCB_Err
 Set myCommandBar = CommandBars.Add(Name:="Sample Toolbar", Position:= _
     msoBarFloating)
  myCommandBar.Visible = True
 Set myCommandBarCtl = myCommandBar.Controls.Add(msoControlComboBox)
  With myCommandBarCtl
     .Caption = "Drop Down"
     .Width = 100
     .AddItem "Create Button", 1
     .AddItem "Remove Button", 2
     .DropDownWidth = 100
     .OnAction = "=AddRemoveButton()"
  End With
  Exit Sub

AddNewCB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub
Function AddRemoveButton()

  Dim myCommandBar As CommandBar, CBCombo As CommandBarComboBox
  Dim CBNewButton As CommandBarButton
  On Error GoTo AddRemoveButton_Err
  Set myCommandBar = CommandBars("Sample Toolbar")
  Set CBCombo = myCommandBar.Controls(3)
  Select Case CBCombo.ListIndex
     Case 1
        Set CBNewButton = myCommandBar.Controls.Add(Type:=msoControlButton)
        With CBNewButton
           .Caption = "New Button"
           .Style = msoButtonCaption
           .BeginGroup = True
           .Tag = "New Button"
           .OnAction = "=MsgBox(""This is a new button!"")"
        End With
     Case 2
        Set CBNewButton = myCommandBar.FindControl(Tag:="New Button")
        CBNewButton.Delete
  End Select
  Exit Function

AddRemoveButton_Err:

  If Err.number = 91 Then
     msgBox "Cannot remove button that does not exist!"
     Exit Function
  Else
    msgBox "Error " & Err.number & vbCr & Err.Description
    Exit Function
  End If

End Function

</source>
   
  

Creating a Toolbar and assign its action

   <source lang="vb">

Function ToggleButton()

  Dim CBButton As CommandBarControl
  On Error GoTo ToggleButton_Err
  Set CBButton = CommandBars("Sample Toolbar").Controls(1)
  CBButton.Visible = Not CBButton.Visible
  Exit Function

ToggleButton_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Function

End Function
Sub AddNewCB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  On Error GoTo AddNewCB_Err
 Set myCommandBar = CommandBars.Add(Name:="Sample Toolbar", Position:= _
     msoBarFloating)
  myCommandBar.Visible = True
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .FaceId = 1000
     .Caption = "Toggle Button"
     .TooltipText = "Toggle First Button"
     .OnAction = "=ToggleButton()"
  End With
  Exit Sub

AddNewCB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub

</source>
   
  

Creating a Toolbar and display MsgBox in its action

   <source lang="vb">

Sub AddNewCB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  On Error GoTo AddNewCB_Err
 Set myCommandBar = CommandBars.Add(Name:="Sample Toolbar", Position:= _
     msoBarFloating)
  myCommandBar.Visible = True
 Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlButton)
  With myCommandBarCtl
     .Caption = "Button"
     .Style = msoButtonCaption
     .TooltipText = "Display Message Box"
     .OnAction = "=MsgBox(""You pressed a toolbar button!"")"
  End With
  
  Exit Sub

AddNewCB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub

</source>
   
  

Custom Toolbars

   <source lang="vb">

Private tlbMyToolbar As CommandBar
«Add tool bar
Sub AddToolbar()

   Dim tlbMyButton As CommandBarButton
   Set tlbMyToolbar = Application.rumandBars.Add( _
       name:=" Example Toolbar", _
       Position:=msoBarFloating, _
       Temporary:=True)
   tlbMyToolbar.Visible = True
   Set tlbMyButton = tlbMyToolbar.Controls.Add( _
       Type:=msoControlButton, _
       Temporary:=True)
   tlbMyButton.Style = msoButtonIconAndCaption
   tlbMyButton.Picture = LoadPicture(ActiveWorkbook.Path & "myImage.bmp")
   tlbMyButton.Caption = "Test"

End Sub

</source>
   
  

deletes a control that has a caption of SortButton.

   <source lang="vb">

Sub commandBar()

   CommandBars("MyToolbar").Controls("SortButton").Delete

End Sub

</source>
   
  

Determines if a given command bar name exists

   <source lang="vb">

Sub TestCommandBarUtilities()

   Debug.Print CommandBarExists("Worksheet Menu Bar") 
   Debug.Print CommandBarExists("Formatting") 
   Debug.Print CommandBarExists("Not a command bar") 

End Sub
Function CommandBarExists(sName As String) As Boolean

   Dim s As String 
   On Error GoTo bWorksheetExistsErr 
   s = Application.rumandBars(sName).Name 
   CommandBarExists = True 
   Exit Function 

bWorksheetExistsErr:

   CommandBarExists = False 

End Function

</source>
   
  

Display Control Detail

   <source lang="vb">

Private Sub DisplayControlDetail()

   Dim cb As CommandBar 
   Dim cbc As CommandBarControl 
   On Error Resume Next 
   For Each cb In Application.rumandBars 
       For Each cbc In cb.Controls 
           Debug.Print Replace(cbc.Caption, "&", "") 
           Debug.Print cbc.Caption 
           Debug.Print cbc.Index 
           Debug.Print cbc.BuiltIn 
           Debug.Print cbc.Enabled 
           Debug.Print cbc.Visible 
           Debug.Print cbc.IsPriorityDropped 
           Debug.Print cbc.Priority 
           Debug.Print TranslateControlType(cbc.Type) 
           Debug.Print cbc.Controls.Count 
       Next 
   Next
   Set cbc = Nothing 

End Sub
Function TranslateControlType(vType As MsoControlType) As String

   Dim sType As String 
   Select Case vType 
       Case Is = MsoControlType.msoControlActiveX 
           sType = "ActiveX" 
       Case Is = MsoControlType.msoControlAutoCompleteCombo 
           sType = "Auto Complete Combo" 
       Case Is = MsoControlType.msoControlButton 
           sType = "Button" 
       Case Is = MsoControlType.msoControlButtonDropdown 
           sType = "Button Dropdown" 
       Case Is = MsoControlType.msoControlButtonPopup 
           sType = "Button Popup" 
       Case Is = MsoControlType.msoControlComboBox 
           sType = "Combo Box" 
       Case Is = MsoControlType.msoControlCustom 
           sType = "Custom" 
       Case Is = MsoControlType.msoControlDropdown 
           sType = "Dropdown" 
       Case Is = MsoControlType.msoControlEdit 
           sType = "Edit" 
       Case Is = MsoControlType.msoControlExpandingGrid 
           sType = "Expanding Grid" 
       Case Is = MsoControlType.msoControlGauge 
           sType = "Gauge" 
       Case Is = MsoControlType.msoControlGenericDropdown 
           sType = "Generic Dropdown" 
       Case Is = MsoControlType.msoControlGraphicCombo 
           sType = "Graphic Combo" 
       Case Is = MsoControlType.msoControlGraphicDropdown 
           sType = "Graphic Dropdown" 
       Case Is = MsoControlType.msoControlGraphicPopup 
           sType = "Graphic Popup" 
       Case Is = MsoControlType.msoControlGrid 
           sType = "Grid" 
       Case Is = MsoControlType.msoControlLabel 
           sType = "Label" 
       Case Is = MsoControlType.msoControlLabelEx 
           sType = "Label Ex" 
       Case Is = MsoControlType.msoControlOCXDropdown 
           sType = "OCX Dropdown" 
       Case Is = MsoControlType.msoControlPane 
           sType = "Pane" 
       Case Is = MsoControlType.msoControlPopup 
           sType = "Popup" 
       Case Is = MsoControlType.msoControlSpinner 
           sType = "Spinner" 
       Case Is = MsoControlType.msoControlSplitButtonMRUPopup 
           sType = "Split Button MRU Popup" 
       Case Is = MsoControlType.msoControlSplitButtonPopup 
           sType = "Split Button Popup" 
       Case Is = MsoControlType.msoControlSplitDropdown 
           sType = "Split Dropdown" 
       Case Is = MsoControlType.msoControlSplitExpandingGrid 
           sType = "Split Expanding Grid" 
       Case Is = MsoControlType.msoControlWorkPane 
           sType = "Work Pane" 
       Case Else 
           sType = "Unknown control type" 
   End Select 
   TranslateControlType = sType 

End Function

</source>
   
  

   <source lang="vb">

Private Sub Worksheet_BeforeRightClick(ByVal Target As Excel.Range, Cancel As Boolean)

   CommandBars("MyShortcut").ShowPopup
   Cancel = True

End Sub

</source>
   
  

displays the Caption property for the first Control object contained in the Standard toolbar, whose index is 3.

   <source lang="vb">

Sub Test()

   MsgBox CommandBars(3).Controls(1).Caption

End Sub

</source>
   
  

Finding Visible Controls with FindControls

   <source lang="vb">

Sub FindVisibleControls()

   Dim ctrls As CommandBarControls
   Dim ctrl As CommandBarControl
   Set ctrls = Application.rumandBars.FindControls(, , , True)
   For Each ctrl In ctrls
       Debug.Print ctrl.Parent.name
       Debug.Print ctrl.Caption
       Debug.Print ctrl.Index
       Debug.Print ctrl.ID
       Debug.Print ctrl.Enabled
       Debug.Print ctrl.Visible
       Debug.Print ctrl.IsPriorityDropped
       Debug.Print TranslateControlType(ctrl.Type)
   Next
   Set ctrl = Nothing
   Set ctrls = Nothing

End Sub
Function TranslateControlType(vType As MsoControlType) As String

   Dim sType As String
   Select Case vType
       Case Is = MsoControlType.msoControlActiveX
           sType = "ActiveX"
       Case Is = MsoControlType.msoControlAutoCompleteCombo
           sType = "Auto Complete Combo"
       Case Is = MsoControlType.msoControlButton
           sType = "Button"
       Case Is = MsoControlType.msoControlButtonDropdown
           sType = "Button Dropdown"
       Case Is = MsoControlType.msoControlButtonPopup
           sType = "Button Popup"
       Case Is = MsoControlType.msoControlComboBox
           sType = "Combo Box"
       Case Is = MsoControlType.msoControlCustom
           sType = "Custom"
       Case Is = MsoControlType.msoControlDropdown
           sType = "Dropdown"
       Case Is = MsoControlType.msoControlEdit
           sType = "Edit"
       Case Is = MsoControlType.msoControlExpandingGrid
           sType = "Expanding Grid"
       Case Is = MsoControlType.msoControlGauge
           sType = "Gauge"
       Case Is = MsoControlType.msoControlGenericDropdown
           sType = "Generic Dropdown"
       Case Is = MsoControlType.msoControlGraphicCombo
           sType = "Graphic Combo"
       Case Is = MsoControlType.msoControlGraphicDropdown
           sType = "Graphic Dropdown"
       Case Is = MsoControlType.msoControlGraphicPopup
           sType = "Graphic Popup"
       Case Is = MsoControlType.msoControlGrid
           sType = "Grid"
       Case Is = MsoControlType.msoControlLabel
           sType = "Label"
       Case Is = MsoControlType.msoControlLabelEx
           sType = "Label Ex"
       Case Is = MsoControlType.msoControlOCXDropdown
           sType = "OCX Dropdown"
       Case Is = MsoControlType.msoControlPane
           sType = "Pane"
       Case Is = MsoControlType.msoControlPopup
           sType = "Popup"
       Case Is = MsoControlType.msoControlSpinner
           sType = "Spinner"
       Case Is = MsoControlType.msoControlSplitButtonMRUPopup
           sType = "Split Button MRU Popup"
       Case Is = MsoControlType.msoControlSplitButtonPopup
           sType = "Split Button Popup"
       Case Is = MsoControlType.msoControlSplitDropdown
           sType = "Split Dropdown"
       Case Is = MsoControlType.msoControlSplitExpandingGrid
           sType = "Split Expanding Grid"
       Case Is = MsoControlType.msoControlWorkPane
           sType = "Work Pane"
       Case Else
           sType = "Unknown control type"
   End Select
   TranslateControlType = sType

End Function

</source>
   
  

Get the type of CommandBars

   <source lang="vb">

Sub listCommandBars()

  Dim comBar As CommandBar
  Dim comBarType As String
  
  For Each comBar In CommandBars
     Select Case comBar.Type
     
     Case msoBarTypeNormal
       comBarType = "Toolbar"
     Case msoBarTypeMenuBar
       comBarType = "Menu Bar"
     Case msoBarTypePopup
       comBarType = "Shortcut"
     End Select
     
     Debug.Print comBar.Index, comBar.Name, comBarType, comBar.Visible
   Next

End Sub

</source>
   
  

how your VBA code can change the position of a toolbar.

   <source lang="vb">

Sub MoveToolbar()

   With CommandBars("MyToolbar")
       OldLeft = .Left
       OldTop = .Top
       For i = 1 To 60
           .Left = Int(vidWidth * Rnd)
           .Top = Int(vidHeight * Rnd)
           DoEvents
       Next i
       .Left = OldLeft
       .Top = OldTop
   End With

End Sub

</source>
   
  

Inspecting a CommandBar

   <source lang="vb">

Sub DisplayGeneralInfo()

   Dim cb As CommandBar 
   For Each cb In Application.rumandBars 
     Debug.Print "Name:" & cb.Name 
     Debug.Print "Index:" & cb.Index 
     Debug.Print "Built In:" & cb.BuiltIn 
     Debug.Print "Enabled:"  cb.Enabled 
     Debug.Print "Visible:" & cb.Visible 
     Debug.Print "Type:" & TranslateCommandBarType(cb.Type) 
     Debug.Print "Position:" & TranslateCommandBarPosition(cb.Position) 
     Debug.Print "Control Count:" & cb.Controls.Count 
   Next

End Sub
Function TranslateCommandBarPosition(vType As MsoBarPosition) As String

   Dim sPosition As String 
   Select Case vType 
       Case Is = MsoBarPosition.msoBarBottom 
           sPosition = "Bottom" 
       Case Is = MsoBarPosition.msoBarFloating 
           sPosition = "Floating" 
       Case Is = MsoBarPosition.msoBarLeft 
           sPosition = "Left" 
       Case Is = MsoBarPosition.msoBarMenuBar 
               sPosition = "Menu Bar" 
       Case Is = MsoBarPosition.msoBarPopup 
           sPosition = "Popup" 
       Case Is = MsoBarPosition.msoBarRight 
           sPosition = "Right" 
       Case Is = MsoBarPosition.msoBarTop 
           sPosition = "Top" 
       Case Else 
           sPosition = "Unknown position" 
   End Select 
   TranslateCommandBarPosition = sPosition 

End Function
Function TranslateCommandBarType(vType As MsoBarType) As String

   Dim sType As String 
   Select Case vType 
       Case Is = MsoBarType.msoBarTypeMenuBar 
           sType = "Menu Bar" 
       Case Is = MsoBarType.msoBarTypeNormal 
           sType = "Normal" 
       Case Is = MsoBarType.msoBarTypePopup 
           sType = "Popup" 
       Case Else 
           sType = "Unknown type" 
   End Select 
   TranslateCommandBarType = sType 

End Function

</source>
   
  

Listing all controls on all toolbars

   <source lang="vb">

Sub ShowAllToolbarControls()

   For Each myCommandBar In CommandBars
       If myCommandBar.Type = msoBarTypeNormal Then
           Debug.Print myCommandBar.name
           For Each ctl In myCommandBar.Controls
               Debug.Print ctl.Caption
           Next ctl
       End If
   Next myCommandBar

End Sub

</source>
   
  

Listing the controls on a command bar

   <source lang="vb">

Sub ShowControlCaptions()

   Dim myCommandBar As commandBar
   Set myCommandBar = CommandBars("Standard")
   For Each ctl In myCommandBar.Controls
       Debug.Print ctl.Caption
   Next ctl
</source>
   
  

Properties of CommandBar controls

   <source lang="vb">

Sub ShowShortcutMenuItems()

 Dim myCommandBar As CommandBar
 Dim Ctl As CommandBarControl
 Application.ScreenUpdating = False
 For Each myCommandBar In Application.rumandBars
   If myCommandBar.Type = msoBarTypePopup Then
     Debug.Print  myCommandBar.Index
     Debug.Print  myCommandBar.Name
     For Each Ctl In myCommandBar.Controls
       If Ctl.Visible Then
         Debug.Print  Ctl.Caption
       Else
         Debug.Print  "<" & Ctl.Caption & ">"
       End If
    Next Ctl
  End If
 Next myCommandBar

End Sub

</source>
   
  

Rather than use an index number to refer to a control, you can use its Caption property setting

   <source lang="vb">

Sub Test2()

   MsgBox CommandBars("Standard").Controls("New").Caption

End Sub

</source>
   
  

Referring to command bars

   <source lang="vb">

Function CommandBarExists(n) As Boolean

   Dim cb As CommandBar
   For Each cb In CommandBars
       If UCase(cb.Name) = UCase(n) Then
           CommandBarExists = True
           Exit Function
       End If
   Next cb
   CommandBarExists = False

End Function

</source>
   
  

Removes a toolbar specified by the name passed in

   <source lang="vb">

Sub RemoveToolbar(tlbarName As String)

   Dim myCommandBar As CommandBar
   For Each myCommandBar In Application.rumandBars
       If myCommandBar.Name = tlbarName Then
           myCommandBar.Delete
           Exit For
       End If
   Next

End Sub

</source>
   
  

Removing all toolbars and then restoring them

   <source lang="vb">

Sub HideAllToolbars()

   Dim toolBar As commandBar
   Dim toolBarNum As Integer
   Dim toolBarSheet As Worksheet
   Set toolBarSheet = Sheets("Sheet1")
   Application.ScreenUpdating = False
   toolBarSheet.Cells.Clear
   
   toolBarNum = 0
   For Each toolBar In CommandBars
       If toolBar.Type = msoBarTypeNormal Then
           If toolBar.Visible Then
               toolBarNum = toolBarNum + 1
               toolBar.Visible = False
               toolBarSheet.Cells(toolBarNum, 1) = toolBar.name
           End If
       End If
   Next toolBar
   Application.ScreenUpdating = True

End Sub

</source>
   
  

   <source lang="vb">

Sub MakeMenuBar()

   Dim NewMenuBar As commandBar
   Set NewMenuBar = CommandBars.Add(MenuBar:=True)
   With NewMenuBar
       .name = "MyMenuBar"
       .Visible = True
   End With
   
   CommandBars("Worksheet Menu Bar") _
    .Controls(1).Copy Bar:=CommandBars("MyMenuBar")
   Set NewMenu = NewMenuBar.Controls.Add _
     (Type:=msoControlPopup)
   NewMenu.Caption = "&Commands"
   Set NewItem = NewMenu.Controls.Add(Type:=msoControlButton)
   With NewItem
       .Caption = "&Restore Normal Menu"
       .OnAction = "DeleteMenuBar"
   End With
   Set NewItem = NewMenu.Controls.Add(Type:=msoControlButton)
   With NewItem
       .Caption = "&Help"
       .OnAction = "DeleteMenuBar"
   End With

End Sub
Sub DeleteMenuBar()

   On Error Resume Next
   CommandBars("MyMenuBar").Delete
   On Error GoTo 0

End Sub

</source>
   
  

Reset CommandBar

   <source lang="vb">

Sub ResetAll()

   Dim myCommandBar As CommandBar
   For Each myCommandBar In Application.rumandBars
       If myCommandBar.Type = msoBarTypePopup Then
           myCommandBar.Reset
           myCommandBar.Enabled = True
       End If
   Next myCommandBar

End Sub

</source>
   
  

   <source lang="vb">

Private Sub ResetCommandBar()

   Application.rumandBars("Worksheet Menu Bar").Reset 

End Sub

</source>
   
  

Restore tool bar

   <source lang="vb">

Sub RestoreToolbars()

   Dim toolBarSheet As Worksheet
   Set toolBarSheet = Sheets("toolBarSheet")
   Application.ScreenUpdating = False
   On Error Resume Next
   For Each Cell In toolBarSheet.range("A:A") _
     .SpecialCells(xlCellTypeConstants)
       CommandBars(Cell.value).Visible = True
   Next Cell
   Application.ScreenUpdating = True

End Sub

</source>
   
  

Save list of all predefined commands and their ID numbers in a file

   <source lang="vb">

Sub IdList()

 On Error Resume Next
 If Application.Version >= 10# Then Exit Sub
 Dim c As CommandBar, i
 Set c = CommandBars.Add
 Open ThisWorkbook.Path + "CommandBar.txt" For Output As #1
 For i = 0 To 32
   c.Controls.Add Id:=i
   If c.Controls(1).Caption <> "" And _
      c.Controls(1).Caption <> "[Command not available]" And _
      c.Controls(1).Caption <> "custom" Then
     Print #1, i, c.Controls(1).Caption
   End If
   c.Controls(1).Delete
 Next i
 c.Delete
 Close #1

End Sub

</source>
   
  

Set Control style, Action, group, faceid and caption

   <source lang="vb">

Sub AddNewMB()

  Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
  Dim myCommandBarSubCtl As CommandBarControl
  On Error GoTo AddNewMB_Err
  Set myCommandBar = CommandBars.Add(Name:="Sample Menu Bar", Position:= _
     msoBarTop, MenuBar:=True, Temporary:=False)
  myCommandBar.Visible = True
  myCommandBar.Protection = msoBarNoMove
  Set myCommandBarCtl = myCommandBar.Controls.Add(Type:=msoControlPopup)
  myCommandBarCtl.Caption = "Displa&y"
  Set myCommandBarSubCtl = myCommandBarCtl.Controls.Add(Type:=msoControlButton)
  With myCommandBarSubCtl
     .Style = msoButtonIconAndCaption
     .Caption = "S&ample Menu Disable"
     .FaceId = 59
     .OnAction = "=SampleMenuDisable()"
     .Parameter = 1
     .BeginGroup = True
  End With

AddNewMB_Err:

  msgBox "Error " & Err.number & vbCr & Err.Description
  Exit Sub

End Sub
Function SampleMenuDisable()

  Application.rumandBars("Sample Menu Bar").Visible = False
  Application.rumandBars("Menu Bar").Visible = True

End Function

</source>
   
  

sets the FaceId property of the first button on the MyToolbar toolbar image to 45, which is the code number for a mailbox icon.

   <source lang="vb">

Sub faceID()

   CommandBars("MyToolbar").Controls(1).FaceId = 45

End Sub

</source>
   
  

Show All Toolbar Controls

   <source lang="vb">

Sub ShowAllToolbarControls()

   Cells.Clear
   Row = 1
   For Each myCommandBar In CommandBars
       If myCommandBar.Type = msoBarTypeNormal Then
           Cells(Row, 1) = myCommandBar.Name
           For Each ctl In myCommandBar.Controls
               Cells(Row, 2) = ctl.Caption
               Row = Row + 1
           Next ctl
       End If
   Next myCommandBar

End Sub

</source>
   
  

Show CommandBar Names

   <source lang="vb">

Sub ShowCommandBarNames()

   Cells.Clear
   Row = 1
   For Each myCommandBar In CommandBars
       Cells(Row, 1) = myCommandBar.Index
       Cells(Row, 2) = myCommandBar.Name
       Select Case myCommandBar.Type
           Case msoBarTypeNormal
               Cells(Row, 3) = "Toolbar"
           Case msoBarTypeMenuBar
               Cells(Row, 3) = "Menu Bar"
           Case msoBarTypePopUp
               Cells(Row, 3) = "Shortcut"
       End Select
       Row = Row + 1
   Next myCommandBar

End Sub

</source>
   
  

show/hide check symbol

   <source lang="vb">

Sub MenuCommand2_OnAction()

 With CommandBars.ActionControl
   If .State = msoButtonDown Then
     .State = msoButtonUp
   Else
     .State = msoButtonDown
   End If
 End With

End Sub

</source>
   
  

Shows or hides a command bar.

   <source lang="vb">

Sub TestCommandBarUtilities()

   ShowCommandBar "Borders", True 

End Sub
Sub ShowCommandBar(sName As String, bShow As Boolean)

   If CommandBarExists(sName) Then 
       Application.rumandBars(sName).Visible = bShow 
   End If 

End Sub

</source>
   
  

simply copies the NumberFormat property of the ActiveCell to the Caption property of the button control.

   <source lang="vb">

Sub UpdateToolbar()

   On Error Resume Next
   CommandBars("Number Format").Controls(1).Caption = ActiveCell.NumberFormat
   If Err <> 0 Then CommandBars("Number Format").Controls(1).Caption = ""

End Sub

</source>
   
  

The custom toolbar is removed with this procedure

   <source lang="vb">

Sub RemoveToolBar()

   On Error Resume Next
   Application.rumandBars("ExcelVBADummies").Delete

End Sub
Sub Main()

 Debug.Print FirstName()

End Sub

 Function FirstName()
      Dim FullName As String
      Dim FirstSpace As Integer
      FullName = Application.userName
      FirstSpace = InStr(FullName, " ")
      If FirstSpace = 0 Then
          FirstName = FullName
      Else
          FirstName = Left(FullName, FirstSpace - 1)
      End If
 End Function
</source>
   
  

The Protection constants are additive: apply different types of protection with a single command

   <source lang="vb">

Sub commandBar()

   Set cb = CommandBars("MyToolbar")
   cb.Protection = msoBarNoCustomize + msoBarNoMove

End Sub

</source>
   
  

The Protection property of a CommandBar object provides you with many options for protecting a CommandBar.

   <source lang="vb">

Sub commdBar()

   CommandBars("MyToolbar").Protection = msoBarNoCustomize

End Sub

</source>
   
  

This toolbar exists only when the cell pointer falls within a given range

   <source lang="vb">

Sub CreateToolbar()

   Dim myBar As commandBar
   Dim Button As CommandBarButton
   
   Set myBar = CommandBars.Add
   For i = 1 To 4
       Set Button = myBar.Controls.Add(msoControlButton)
       With Button
           .OnAction = "Button" & i
           .FaceId = i + 37
       End With
   Next i
   myBar.name = "myBar"

End Sub

</source>
   
  

To delete a control from a CommandBar object, use the Delete method of the Controls collection

   <source lang="vb">

Sub delBar()

   CommandBars("MyToolbar").Controls(1).Delete

End Sub

</source>
   
  

Translates a MsoBarPosition enumeration into a text description of the bar position.

   <source lang="vb">

Sub Inventory()

   Dim cb As commandBar
   For Each cb In Application.rumandBars
       Debug.Print TranslateCommandBarPosition(cb.Position)
   Next
   Set cb = Nothing

End Sub
Function TranslateCommandBarPosition(vType As MsoBarPosition) As String

   Dim sPosition As String
   Select Case vType
       Case Is = MsoBarPosition.msoBarBottom
           sPosition = "Bottom"
       Case Is = MsoBarPosition.msoBarFloating
           sPosition = "Floating"
       Case Is = MsoBarPosition.msoBarLeft
           sPosition = "Left"
       Case Is = MsoBarPosition.msoBarMenuBar
               sPosition = "Menu Bar"
       Case Is = MsoBarPosition.msoBarPopup
           sPosition = "Popup"
       Case Is = MsoBarPosition.msoBarRight
           sPosition = "Right"
       Case Is = MsoBarPosition.msoBarTop
           sPosition = "Top"
       Case Else
           sPosition = "Unknown position"
   End Select
   TranslateCommandBarPosition = sPosition

End Function

</source>
   
  

Translates a MsoBarType enumeration into a text description of the bar type.

   <source lang="vb">

Sub Inventory()

   Dim cb As commandBar
   For Each cb In Application.rumandBars
       Debug.Print TranslateCommandBarType(cb.Type)
   Next
   Set cb = Nothing

End Sub
Function TranslateCommandBarType(vType As MsoBarType) As String

   Dim sType As String
   Select Case vType
       Case Is = MsoBarType.msoBarTypeMenuBar
           sType = "Menu Bar"
       Case Is = MsoBarType.msoBarTypeNormal
           sType = "Normal"
       Case Is = MsoBarType.msoBarTypePopup
           sType = "Popup"
       Case Else
           sType = "Unknown type"
   End Select
   TranslateCommandBarType = sType

End Function

</source>
   
  

Translates a MsoControlType enumeration into a text description of the control type.

   <source lang="vb">

Private Sub DisplayControlDetail()

   Dim cb As CommandBar 
   Dim cbc As CommandBarControl 
   On Error Resume Next 
   For Each cb In Application.rumandBars 
       For Each cbc In cb.Controls 
           Debug.Print cbc.Caption 
           Debug.Print TranslateControlType(cbc.Type) 
       Next 
   Next
   Set cbc = Nothing 

End Sub
Function TranslateControlType(vType As MsoControlType) As String

   Dim sType As String 
   Select Case vType 
       Case Is = MsoControlType.msoControlActiveX 
           sType = "ActiveX" 
       Case Is = MsoControlType.msoControlAutoCompleteCombo 
           sType = "Auto Complete Combo" 
       Case Is = MsoControlType.msoControlButton 
           sType = "Button" 
       Case Is = MsoControlType.msoControlButtonDropdown 
           sType = "Button Dropdown" 
       Case Is = MsoControlType.msoControlButtonPopup 
           sType = "Button Popup" 
       Case Is = MsoControlType.msoControlComboBox 
           sType = "Combo Box" 
       Case Is = MsoControlType.msoControlCustom 
           sType = "Custom" 
       Case Is = MsoControlType.msoControlDropdown 
           sType = "Dropdown" 
       Case Is = MsoControlType.msoControlEdit 
           sType = "Edit" 
       Case Is = MsoControlType.msoControlExpandingGrid 
           sType = "Expanding Grid" 
       Case Is = MsoControlType.msoControlGauge 
           sType = "Gauge" 
       Case Is = MsoControlType.msoControlGenericDropdown 
           sType = "Generic Dropdown" 
       Case Is = MsoControlType.msoControlGraphicCombo 
           sType = "Graphic Combo" 
       Case Is = MsoControlType.msoControlGraphicDropdown 
           sType = "Graphic Dropdown" 
       Case Is = MsoControlType.msoControlGraphicPopup 
           sType = "Graphic Popup" 
       Case Is = MsoControlType.msoControlGrid 
           sType = "Grid" 
       Case Is = MsoControlType.msoControlLabel 
           sType = "Label" 
       Case Is = MsoControlType.msoControlLabelEx 
           sType = "Label Ex" 
       Case Is = MsoControlType.msoControlOCXDropdown 
           sType = "OCX Dropdown" 
       Case Is = MsoControlType.msoControlPane 
           sType = "Pane" 
       Case Is = MsoControlType.msoControlPopup 
           sType = "Popup" 
       Case Is = MsoControlType.msoControlSpinner 
           sType = "Spinner" 
       Case Is = MsoControlType.msoControlSplitButtonMRUPopup 
           sType = "Split Button MRU Popup" 
       Case Is = MsoControlType.msoControlSplitButtonPopup 
           sType = "Split Button Popup" 
       Case Is = MsoControlType.msoControlSplitDropdown 
           sType = "Split Dropdown" 
       Case Is = MsoControlType.msoControlSplitExpandingGrid 
           sType = "Split Expanding Grid" 
       Case Is = MsoControlType.msoControlWorkPane 
           sType = "Work Pane" 
       Case Else 
           sType = "Unknown control type" 
   End Select 
   TranslateControlType = sType 

End Function

</source>
   
  

   <source lang="vb">

Sub ListShortCutMenus()

   For Each myCommandBar In CommandBars
       If myCommandBar.Type = msoBarTypePopup Then
           Debug.Print myCommandBar.Index
           Debug.Print myCommandBar.name
           For col = 1 To myCommandBar.Controls.Count
               Debug.Print myCommandBar.Controls(col).Caption
           Next col
       End If
   Next myCommandBar

End Sub

</source>

In This Chapter

Using toolbars in Excel

► Customizing toolbars in different ways Creating different images on toolbar buttons
► Manipulating toolbars with VBA
Excel is definitely not a toolbar-challenged product. It comes with dozens of built-in toolbars, and constructing new toolbars is very easy. This chapter shows you how to manipulate toolbars with VBA.

Introducing CommandBars

When programming in Excel, a toolbar is technically known as a CommandBar object. In fact, a toolbar is just one of the three types of CommandBar objects:
Toolbar. A floating bar with one or more clickable controls. This chapter focuses on this type of CommandBar.
Menu bar. The two built-in menu bars are the Worksheet menu bar and the Chart menu bar. See Chapter 20.
Shortcut menu. These menus pop up when you right-click an object. See Chapter 20.

Customizing Toolbars

The following list summarizes the ways you can customize toolbars. (I discuss these topics in detail later in this chapter.)
Remove toolbar controls from built-in toolbars. You can get rid of toolbar controls that you never use, reduce screen clutter, and free up a few pixels of screen space, to boot.
Add toolbar controls to built-in toolbars. You can add as many toolbar controls as you want to any toolbar. The controls can be custom buttons or buttons copied from other toolbars, or they can come from the stock of toolbar controls that Excel provides for you. And, of course, you can attach your VBA macros to these buttons.
Create new toolbars. You can create as many new toolbars as you like, with toolbar buttons (or other types of controls) from any source.
Change the functionality of built-in toolbar controls. You do this by attaching your own macro to a built-in toolbar button.
Change the image that appears on any toolbar button. Excel includes a rudimentary but functional toolbar button editor. You can also change a toolbar’s image by using several other techniques.
Don’t be afraid to experiment with toolbars. If you mess up a built-in toolbar, you can easily reset it to its default state:
1. Choose View Toolbars Customize.
2. Select the toolbar in the list.
3. Click the Reset button.

How Excel handles toolbars

When you start Excel, it displays the same toolbar configuration that was in effect the last time you used the program. Did you ever wonder how Excel keeps track of this information?
When you exit Excel, it updates a file called EXCEL11.XLB. The exact location (and even the name) of this file varies, but you can use Windows’ Find File feature to locate the file. (Search for *.XLB.) This file stores all of your custom toolbars, as well as information about the on-screen location of each toolbar and which toolbars are visible.
If you need to restore the toolbars to their previous configuration, choose FileOOpen and open your XLB file. This restores your toolbar configuration to the way it was when you started the current session of Excel. You also can make a copy of the XLB file and give it a different name. Doing so lets you store multiple toolbar configurations that you can load any time. And if you’ve made lots of toolbar changes and want to return to Excel’s original toolbar state, just delete your XLB file and restart Excel. It creates a new one for you.

Working with Toolbars

As you probably know, you can display as many toolbars as you like. A toolbar can be either docked or floating. A docked toolbar is fixed in place at the top, bottom, left, or right edge of Excel’s workspace. Floating toolbars appear in an always-on-top window, which means that they are never obscured by other windows. You can change the dimensions of a floating toolbar by dragging a border.
As shown in Figure 19-1, right-clicking any toolbar or toolbar button displays a shortcut menu that lets you hide or display a toolbar. This shortcut menu, however, does not display the names of all toolbars. For a complete list of toolbars, use the Customize dialog box. This dialog box lets you hide or display toolbars (among other things).
Right-clicking a toolbar or a toolbar button displays this shortcut menu.
Figure 19-1:
Right-clicking a toolbar or a toolbar button displays this shortcut menu.

You can access the Customize dialog box in two ways:

Choose View Toolbars Customize.
Right-click a toolbar and choose Customize from the shortcut menu.

The Toolbars tab

The Customize dialog box’s Toolbars tab, shown in Figure 19-2, lists all the available toolbars, including toolbars you have created. This dialog box also lists the two menu bars (Worksheet and Chart), which are similar to toolbars.
The Toolbars tab is in the Customize dialog box.
Figure 19-2:
The Toolbars tab is in the Customize dialog box.
This section describes how to perform various procedures that involve toolbars.
Hiding or displaying a toolbar: The Toolbars tab displays every toolbar (built-in toolbars and custom toolbars). Add a check mark to display a toolbar; remove the check mark to hide it. The changes take effect immediately.
Creating a new toolbar: Click the New button and enter a name in the New Toolbar dialog box. Excel creates and displays an empty toolbar. You can then add buttons (or menu commands) to the new toolbar. See “Adding and Removing Toolbar Controls” later in this chapter.
Figure 19-3 shows a custom toolbar that I created. This toolbar, called Custom Formatting, contains the formatting tools that I use most frequently. Notice that this toolbar includes drop-down menus as well as standard toolbar buttons.
Renaming a custom toolbar: Select the custom toolbar from the list and click the Rename button. In the Rename Toolbar dialog box, enter a new name. You can’t rename a built-in toolbar.
Deleting a custom toolbar: Select the custom toolbar from the list and click the Delete button. You can’t delete a built-in toolbar.
Deleting a toolbar is one of the few actions in Excel that cannot be undone.
A custom toolbar.
Figure 19-3:
A custom toolbar.
Resetting a built-in toolbar: Select a built-in toolbar from the list and click the Reset button. The toolbar is restored to its default state. Any added custom tools are removed. Any removed default tools are restored. The Reset button is not available when a custom toolbar is selected.
Attaching a toolbar to a workbook: You can share a custom toolbar by attaching it to a workbook. Click the Attach button and you get a new dialog box that lets you select toolbars to attach to a workbook. You can attach any number of toolbars to a workbook — but remember, attaching toolbars increases the size of your workbook. For more about this, see “Distributing Toolbars,” later in this chapter.

Toolbar autosensing

Normally, Excel displays a particular toolbar automatically when you change contexts. This is called autosensing. For example, when you activate a chart, the Chart toolbar appears. When you activate a sheet that contains a pivot table, the PivotTable toolbar appears.
You can easily defeat autosensing by hiding the toolbar: Click its Close button. After you do so, Excel no longer displays that toolbar when you
switch to its former context. You can restore this automatic behavior by displaying the appropriate toolbar when you’re in the appropriate context. Thereafter, Excel reverts to its normal automatic toolbar display when you switch to that context.
You can simulate this type of behavior by writing VBA code. Refer to “Displaying a toolbar when a worksheet is activated,” later in this chapter.

The Commands tab

The Commands tab of the Customize dialog box contains a list of every available tool. Use this tab when you customize a toolbar. This feature is described later in this chapter in “Adding and Removing Toolbar Controls.”

The Options tab

Figure 19-4 shows the Options tab of the Customize dialog box. The options on this tab control how both menus and toolbars behave. The options that affect toolbars are as follows:
The Options tab of the Customize dialog box.
Figure 19-4:
The Options tab of the Customize dialog box.
Using one row for two toolbars: You can save a little bit of valuable screen space by removing the checkmark from the Show Standard and Formatting Toolbars on Two Rows check box to force Excel to stuff both toolbars on a single row. Go ahead with this if you’re running your system at a high screen resolution; you can get more on the screen horizontally. However, you may not want to choose this option if you’re running in a lower screen resolution.
Showing full menus: Perhaps one of Microsoft’s dumbest ideas is adaptive menus. In other words, the software hides menu items that are not used frequently. I’ve never met anyone who likes this. If you find that your menus seem to be missing some commands, select the Always Show Full Menus check box.
Changing the icon size: To change the size of the icons used in toolbars, select or deselect the Large Icons check box. This option affects only the images in buttons. Buttons that contain only text (such as buttons in a menu) are not changed.
Display fancy font names: Some people like the feature for which the drop-down Font list on the Formatting toolbar shows names using the actual font; others despise it. The List Font Names In Their Font check box controls whether Excel does this. Personally, I think using the fonts slows down Excel if you’re working with a lot of fonts.
Toggling the ScreenTips display: ScreenTips are the pop-up messages that display the button names when you pause the mouse pointer over a button. If you find the ScreenTips distracting, deselect the Show ScreenTips on Toolbars check box.
Changing the menu animations: When you select a menu, Excel animates its menu display. Choose whichever animation style you prefer.

Adding and Removing Toolbar Controls

When the Customize dialog box is displayed, Excel is in a special customization mode. You have access to all the commands and options in the Customize dialog box. In addition, you can perform the following actions:
Reposition a control on a toolbar
Move a control to a different toolbar
Copy a control from one toolbar to another
Add new controls to a toolbar using the Commands tab of the Customize dialog box
Change lots of toolbar control attributes
Moving and copying controls
When the Customize dialog box is displayed, you can copy and move toolbar controls freely among any visible toolbars. To move a control, drag it to its new location. The new location can be within the current toolbar or on a different toolbar.
To copy a control, press Ctrl while dragging the control to another toolbar. You can copy a toolbar control within the same toolbar, but you’ve no reason to have multiple copies of a button on the same toolbar.

Inserting a new control

To add a new control to a toolbar, use the Customize dialog box’s Commands tab shown in Figure 19-5.
The Commands tab contains a list of every available control.
Figure 19-5:
The Commands tab contains a list of every available control.
The controls are arranged in 17 categories. When you select a category, the controls in that category appear to the right. Previous versions of Excel had a Description button that, when clicked, described the selected control’s function. For reasons known only to Microsoft, that Description button was removed in Excel 2003.
To add a control to a toolbar, locate it in the Commands tab, click it, and drag it to the toolbar.

Using other toolbar button operations

When Excel is in customization mode (that is, when the Customize dialog box is displayed), you can right-click a toolbar control to display a shortcut menu of additional actions. Figure 19-6 shows the shortcut menu that appears when you right-click a button in customization mode.
These commands are described in the following list. (Note that some of these commands are unavailable for certain toolbar controls.)
Reset: Resets the control to its original state.
Delete: Deletes the control.
Name: Lets you change the control’s name.
Copy Button Image: Copies the control’s image and places it on the Clipboard.
Paste Button Image: Pastes the image from the Clipboard to the control.
Reset Button Image: Restores the control’s original image.
Edit Button Image: Lets you edit the control’s image using the Excel button editor.
Change Button Image: Lets you change the image by selecting from a list of different button images.
Default Style: Displays the control using its default style. (For buttons, the default is image only. For menu items, the default is both image and text.)
Text Only (Always): Always displays text (no image) for the control.
Text Only (In Menus): Displays text (no image) if the control is in a menu bar.
Image and Text: Displays the control’s image and text.
Begin a Group: Inserts a divider in the toolbar. In a drop-down menu, a separator bar appears as a horizontal line between commands. In a toolbar, a separator bar appears as a vertical line.
Assign a Hyperlink: Lets you assign a hyperlink that activates when the control is clicked.
Assign a Macro: Lets you assign a macro that executes when the control is clicked.
In customization mode, right-clicking a toolbar control displays this shortcut menu.
Figure 19-6:
In customization mode, right-clicking a toolbar control displays this shortcut menu.

Distributing Toolbars

If you want to distribute a custom toolbar to other users, store it in a workbook. To store a toolbar in a workbook file, follow these steps:
1. Create the custom toolbar and test it to make sure it works correctly.
2. Activate the workbook that will store the new toolbar.
3. Choose View Toolbars Customize.
4. In the Customize dialog box, click the Toolbars tab.
5. Click the Attach button.
Excel displays the Attach Toolbars dialog box shown in Figure 19-7. This dialog box lists all custom toolbars stored on your system.
6. To attach a toolbar, select it and click the Copy button.
When a toolbar in the Toolbars in Workbook list (right side of the dialog box) is selected, the Copy button changes to a Delete button. You can click the Delete button to remove the selected toolbar from the workbook.
The Attach Toolbars dialog box lets you attach one or more toolbars to a workbook.
Figure 19-7:
The Attach Toolbars dialog box lets you attach one or more toolbars to a workbook.
A toolbar that’s attached to a workbook appears automatically when the workbook is opened, and that toolbar is then saved in the user’s XLB file when Excel closes down. If the user’s workspace already has a toolbar by the same name, however, the toolbar attached to the workbook does not replace the existing one.
The toolbar that’s stored in the workbook is an exact copy of the toolbar at the time you attach it. If you modify the toolbar after attaching it, the changed version is not stored in the workbook automatically. You must manually remove the old toolbar and then attach the new one.

Using VBA to Manipulate Toolbars

As you may expect, you can write VBA code to do things with toolbars. In this section, I provide some background information that you simply must know before you start mucking around with toolbars.

Commanding the CommandBars collection

You manipulate Excel toolbars (and menus, for that matter) by using objects located in the CommandBars collection. The CommandBars collection consists of
All Excel built-in toolbars
Any other custom toolbars that you create
A built-in menu bar named Worksheet menu bar, which appears when a worksheet is active
A built-in menu bar named Chart menu bar, which appears when a chart sheet is active
Any other custom menu bars that you create All built-in shortcut menus
As I mention at the beginning of this chapter, the three types of CommandBar are differentiated by their Type properties. The Type property can be any of these three values:
msoBarTypeNormal: A toolbar (Type = 0) msoBarTypeMenuBar: A menu bar (Type = 1) msoBarTypePopUp: A shortcut menu (Type = 2)

Listing all CommandBar objects

If you’re curious about the objects in the CommandBars collection, enter and execute the following macro. The result is a list of all CommandBar objects in the CommandBars collection, plus any custom menu bars or toolbars. For each CommandBar, the procedure lists its Index, Name, and Type. (The Type can be 0, 1, or 2).
tmp59-10_thumb
Figure 19-8 shows a portion of the result of running this procedure, which is available at this topic’s Web site. As you can see, Excel has a lot of CommandBars.
A VBA macro produced this list of all CommandBar objects.
Figure 19-8:
A VBA macro produced this list of all CommandBar objects.

Referring to CommandBars

You can refer to a particular CommandBar by its Index or by its Name. For example, the Standard toolbar has an Index of 3, so you can refer to the toolbar one of two ways:
tmp59-12_thumb
or
tmp59-13_thumb
For some reason, Microsoft isn’t consistent with CommandBar index numbers across versions of Excel. Therefore, it’s better to refer to a CommandBar by its Name, rather than by its Index.
Referring to controls in a CommandBar
A CommandBar object contains Control objects, which are buttons, menus, or menu items. The following procedure displays the Caption property for the first Control in the Standard toolbar:
tmp59-14_thumb
When you execute this procedure, you see the message box shown in Figure 19-9.
Displaying the Caption property for a control.
Figure 19-9:
Displaying the Caption property for a control.
In some cases, these Control objects can contain other Control objects. For example, the first control on the Drawing toolbar contains other controls. (This also demonstrates that you can include menu items on a toolbar.) The concept of Controls within Controls becomes clearer in Chapter 20, when I discuss menus.

Properties of CommandBar controls

CommandBar controls have a number of properties that determine how the controls look and work. This list contains some of the more useful properties for CommandBar controls:
Caption: The text displayed for the control. If the control shows only an image, the Caption appears when you move the mouse over the control.
FaceID: A number that represents a graphics image displayed next to the control’s text.
BeginGroup: True if a separator bar appears before the control.
OnAction: The name of a VBA macro that executes when the user clicks the control.
BuiltIn: True if the control is an Excel built-in control. Enabled: True if the control can be clicked.
ToolTipText: Text that appears when the user moves the mouse pointer over the control.
When you work with toolbars, you can turn on the macro recorder to see what’s happening in terms of VBA code. Unless you’re editing button images, the steps you take while customizing toolbars generate VBA code. By examining this code, you can discover how Excel arranges the object model for toolbars. The model is pretty simple.

VBA Examples

This section contains a few examples of using VBA to manipulate the Excel toolbars. These examples give you an idea of the types of things you can do, and they can all be modified to suit your needs.

Resetting all built-in toolbars

The following procedure resets all built-in toolbars to their original state:

tmp59-16_thumb
Using the Reset method on a custom toolbar has no effect (and does not generate an error).
Be careful with the preceding routine. Executing it erases all of your customizations to all built-in toolbars. The toolbars will be just as they were when you first installed Excel.

Displaying a toolbar when a worksheet is activated

Assume that you have a workbook (named Budget) that holds your budget information. In addition, assume that you’ve developed a custom toolbar (named Budget Tools) that you use with this workbook. The toolbar should be visible when you work on the Budget sheet; otherwise, it should remain hidden and out of the way.
The following procedures, which are stored in the code window for the This Workbook object, display the Budget Tools toolbar when the Budget workbook is active and hide the toolbar when the Budget workbook is deactivated:
tmp59-17_thumb
For this example go to this topic’s Web site. For more information about using automatic procedures, go to Chapter 11.

Ensuring that an attached toolbar is displayed

As I explained earlier in this chapter, you can attach any number of toolbars to a workbook. But I also noted that the attached toolbar won’t replace an existing toolbar that has the same name.
In some cases, the failure to display a toolbar can present a problem. For example, assume that you distribute a workbook to your coworkers, and this workbook has an attached toolbar that executes your macros. Later, you update the workbook and add some new controls to your attached toolbar. When you distribute this new workbook, the updated toolbar doesn’t display because the old toolbar already exists!
One solution is to simply use a new toolbar name for the updated application. Perhaps a better solution is to write VBA code to delete the toolbar when the workbook closes. That way, the toolbar isn’t stored on the user’s system and you’re assured that the latest copy of your toolbar is always displayed when the workbook opens.
The following procedure, which is stored in the code window for the This Workbook object, displays the toolbar named Budget Tools when the workbook is opened. The Budget Tools toolbar is attached to the workbook.
tmp59-18_thumb

The next procedure, which is also stored in the code window for the This Workbook object, deletes the toolbar named Budget Tools when the workbook is closed:

tmp59-19_thumb
Notice that I use an On Error Resume Next statement to avoid the error message that appears if the toolbar has already been deleted.

Hiding and restoring toolbars

In some cases, you may want to remove all the toolbars when a workbook is opened. It’s only polite, however, to restore the toolbars when your application closes. In this section I present two procedures, both stored in the code window of the This Workbook object.
The Workbook_Open procedure, available at this topic’s Web site, is executed when the workbook is opened. This procedure saves the names of all visible toolbars in column A of Sheet1 and then hides all the toolbars:
tmp59-20_thumb
The following procedure is executed before the workbook is closed. This routine loops through the toolbar names stored on Sheet1 and changes their Visible property to True:
tmp59-21_thumb
Notice that the Workbook_Open routine saves the toolbar names in a worksheet range rather than in an array, ensuring that the toolbar names are still available when the Workbook_BeforeClose routine is executed. Values stored in an array may be lost between the time the Workbook_Open procedure is executed and the Workbook_BeforeClose procedure is executed.

Программное добавление кнопки в контекстное меню ячейки (строки, столбца) из кода VBA Excel. Свойство CommandBars объекта Application.

Свойство Application.CommandBars

Свойство CommandBars объекта Application возвращает коллекцию командных панелей Microsoft Excel.

Примеры командных панелей, вызываемых кликом правой кнопки мыши (контекстных меню):

  • CommandBars(«Cell») – контекстное меню ячейки;
  • CommandBars(«Row») – контекстное меню строки;
  • CommandBars(«Column») – контекстное меню столбца.

Добавление кнопки из кода VBA Excel в контекстное меню ячейки. Кнопки в контекстные меню строк и столбцов добавляются аналогично.

‘Объявляем объектную переменную cmdBarBut

Dim cmdBarBut As CommandBarButton

‘Создаем временную (Temporary:=True) кнопку для контекстного

‘меню ячейки и присваиваем ссылку на нее переменной cmdBarBut

Set cmdBarBut = Application.CommandBars(«Cell»).Controls.Add(Temporary:=True)

With cmdBarBut

   ‘Присваиваем кнопке название

   .Caption = «Новая кнопка»

   ‘Задаем отображение в контекстном меню только названия кнопки

   .Style = msoButtonCaption

   ‘Назначаем кнопке процедуру (макрос)

   .OnAction = «MySub»

End With

Если хотите создать постоянную кнопку для контекстного меню, используйте параметр Temporary метода Controls.Add в значении False, которое применяется по умолчанию:

Set cmdBarBut = Application.CommandBars(«Cell»).Controls.Add

Созданная предыдущим кодом VBA временная кнопка контекстного меню ячейки будет утилизирована только при закрытии приложения Microsoft Excel. Это означает, что если в приложении открыты несколько книг, тогда после закрытия книги с кодом, создавшим кнопку, она продолжит существование и будет доступна из других открытых книг. Если это не желательно, можно удалить кнопку следующей строкой:

Application.CommandBars(«Cell»).Controls(«Новая кнопка»).Delete

Эта же строка удалит и постоянную кнопку.

Примеры добавления и удаления кнопок

Пример 1

Добавление кнопки в контекстное меню ячейки из кода VBA Excel при открытии книги и удаление кнопки при закрытии книги.

Добавление кнопки (код размещается в модуле книги):

Private Sub Workbook_Activate()

Dim cmdBarBut As CommandBarButton

    On Error Resume Next

        Set cmdBarBut = Application.CommandBars(«Cell»).Controls.Add(Temporary:=True)

            With cmdBarBut

               .Caption = «Новая кнопка»

               .Style = msoButtonCaption

               .OnAction = «MySub»

            End With

    On Error GoTo 0

End Sub

Удаление кнопки (код размещается в модуле книги):

Private Sub Workbook_Deactivate()

    On Error Resume Next

        Application.CommandBars(«Cell»).Controls(«Новая кнопка»).Delete

    On Error GoTo 0

End Sub

Вызываемая процедура (код размещается в стандартном модуле):

Sub MySub()

    MsgBox «Кнопка работает!»

End Sub

Пример 2

Добавление кнопки в контекстное меню ячейки из кода VBA Excel при открытии контекстного меню и удаление кнопки при завершении вызываемой процедуры.

Добавление кнопки (код размещается в модуле книги):

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)

Dim cmdBarBut As CommandBarButton

    On Error Resume Next

        With Application

            ‘Удаляем ранее созданную кнопку, если она не была

            ‘нажата и не была удалена назначенным ей макросом

            .CommandBars(«Cell»).Controls(«Новая кнопка»).Delete

            Set cmdBarBut = .CommandBars(«Cell»).Controls.Add(Temporary:=True)

        End With

        With cmdBarBut

           .Caption = «Новая кнопка»

           .Style = msoButtonCaption

           .OnAction = «MySub»

        End With

    On Error GoTo 0

End Sub

Удаление кнопки при закрытии книги, если она при вызове контекстного меню не была нажата и не была удалена назначенным ей макросом (код размещается в модуле книги):

Private Sub Workbook_Deactivate()

    On Error Resume Next

        Application.CommandBars(«Cell»).Controls(«Новая кнопка»).Delete

    On Error GoTo 0

End Sub

Вызываемая процедура с кодом удаления вызвавшей ее кнопки из контекстного меню (код размещается в стандартном модуле):

Sub MySub()

MsgBox «Кнопка работает!»

    On Error Resume Next

        Application.CommandBars(«Cell»).Controls(«Новая кнопка»).Delete

    On Error GoTo 0

End Sub

By using toolbars and shortcut menus, you can provide quick access to commonly used commands. Excel has more than 50 different built-in toolbars and about 60 different shortcut menus, all of which are part of the

CommandBars collection. This collection also contains any new custom toolbars and menus you create. Due to their central location, you can easily make modifications to existing menus and toolbars, or add new ones as needed.

UNDERSTANDING THE COMMANDBARS COLLECTION

The CommandBars collection is part of the Application object, the main object that contains all Excel-related objects.

Each individual toolbar or menu is a separate CommandBar object. You can reference these objects either by an index value or by the object name. For example, the code CommandBars( «Standard» ) references the Standard toolbar. See Appendix A for a list of the built-in toolbars and shortcut menus in Excel.

Excel determines which type of command bar a particular object contains by the value of the Type property. Excel has three types of command bar objects, as described in the following table.

TYPE

INTEGER

CONSTANT

Toolbar

0

msoBarTypeNormal

Menu Bar

1

msoBarTypeMenuBar

ShortCut Menu

2

msoBarTypePopUp

EXISTING MENUS AND TOOLBARS

You can modify menus and toolbars either manually from Excel or you can create subroutines to modify these CommandBar objects. In Excel, you make modifications to toolbars and menus via the Customize command on the Tools menu. From the Customize menu you can add and remove both menu and toolbar options. See Chapter 1 for more information about adding macro references to toolbars and menus.

You can also write a procedure that modifies a particular menu or toolbar by adding or removing options. Each option on a toolbar or menu is a

CommandBarControl object associated with the corresponding CommandBar object. You reference the

CommandBarControls collection using the

Controls property. You add a new option to a toolbar or menu using the Add method.

When you call the Add method with the Controls object, you can apply the optional parameters of the method to specify the type of control to add. The following table describes each of the parameters you can call with the Add method to create a new control. After you add the control, you reference the CommandBarControl properties to set the specific properties for the individual control. See the sections «Add Controls to a Toolbar» and «Add Items to a Menu» for more information on adding options to toolbars and menus.

Continue reading here: Create A Custom Dialog Box

Was this article helpful?

Понравилась статья? Поделить с друзьями:
  • Command line in excel
  • Command functions in excel
  • Command for word find
  • Command for word count
  • Command for microsoft excel