Name

commandbars.Add([Name], [Position], [MenuBar], [Temporary])

Synopsis

Creates a new menu or toolbar as a CommandBar object.

Argument

Settings

Name

The name of the menu or toolbar to create.

Position

An MsoBarPosition constant indicating the docking location of the command bar. Can be one of these settings: msoBarLeft, msoBarTop, msoBarRight, msoBarBottom, msoBarFloating, msoBarPopup, or msoBarMenuBar (Macintosh only). Default is msoBarTop.

MenuBar

True replaces the active menu bar with the menu bar created by Add. Default is False.

Temporary

True prevents the command bar from being saved when Excel closes. False saves the command bar in the user’s .xlb file when Excel closes. Default is False.

When creating context menus, use the Position msoBarPopup. When creating floating toolbars, use the Position msoBarFloating. For example, the following code creates a context menu; then displays it at the coordinates (100, 200):

Sub CreateNewContextMenu( ) Dim cb As CommandBar ' Create a new context menu bar. Set cb = Application.CommandBars.Add("ContextMenu1", _ msoBarPopup, , True) ' Add some items to the menu bar. With cb.Controls.Add(msoControlButton, , , , True) .Caption = "Sample &1" .OnAction = "Sample1" End With With cb.Controls.Add(msoControlButton, , , , True) .Caption = "Sample &2" .OnAction = "Sample2" End With With cb.Controls.Add(msoControlButton, , , , True) .Caption = "Run &All" .OnAction = "TestMenus" .BeginGroup = True End With ' Display this context menu. ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.