Tuesday, December 1, 2009

[Excel] Creating a Custom Menu/Command bar Using VBA Macro and Add-Ins

This macro creates a custom command bar at the bottom part of the Excel window as shown.


Custom Menu/CommandBar Addin
The command bar has three menu items. Each of the menu items are assigned to a macro.
Here is how to go about creating a custom command bar:

Step 1: Create a new Excel file and use the code below to create your own command bar
Step 2: Save the file as an AddIn, for example "Utility.xla".
Step 3: Go to Tools -> Add-ins and browse the addin file you created as shown. Each time Excel is opened, this add-in is called and the Command Bar is ready to use.

Custom Menu/CommandBar Addin



'=========================================================================
' Creating Utility Command Bar with Button Menu Items with Icons
' Copyright vbacentral.blogspot.com
'=========================================================================
Option Explicit

Sub Create_Utility_Menu() Dim MyBar As CommandBar Dim MyPopup As CommandBarPopup Dim MyButton As CommandBarButton ' Delete Menu, if it was already created On Error Resume Next CommandBars("Utility Menu").Delete On Error GoTo 0 ' Create a Command Bar object on the bottom of the Excel window Set MyBar = CommandBars.Add(Name:"Utility Menu", _ Position:=msoBarBottom, Temporary:=True) With MyBar '.Width = 200 .Visible = True Set MyButton = MyBar.Controls.Add(Type:=msoControlButton) With MyButton .Caption = "Move Sheets Around" .Style = msoButtonIconAndCaption 'Other Menu item types include: 'msoButtonAutomatic, msoButtonIcon, msoButtonCaption, or msoButtonIconandCaption .BeginGroup = True 'Assign a macro (in this case macro name is MoveSheets) .OnAction = "MoveSheets" 'Assign a picture icon using predefined Office icons .FaceId = 1771 End With Set MyButton = MyBar.Controls.Add(Type:=msoControlButton) With MyButton .Caption = "Hide/Unhide Sheets" .Style = msoButtonIconAndCaption .BeginGroup = True 'Assign a macro (in this case macro name is HideUnhideSelectedSheets) .OnAction = "HideUnhideSelectedSheets" 'Assign a picture icon using predefined Office icons .FaceId = 488 End With Set MyButton = MyBar.Controls.Add(Type:=msoControlButton) With MyButton .Caption = "Go to Sheet" .Style = msoButtonIconAndCaption .BeginGroup = True 'Assign a macro (in this case macro name is GoToSheet) .OnAction = "GoToSheet" 'Assign a picture icon using predefined Office icons .FaceId = 917 End With End With End Sub

2 comments: