Create or Add to VBA Word Menus 

You can create custom VBA word menus and you can add to existing menus. On this page we will see how you add a new menu called favorite to the main Word menu bar.

Here is the code if you want to copy it...

Sub AddCustomMenu()
Dim cbMenuBar As CommandBar
Dim idHelp As Integer
Dim cbcNewMenu As CommandBarControl

Set cbMenuBar = Application.CommandBars("Menu Bar")
idHelp = cbMenuBar.Controls("Help").Index
On Error Resume Next
Application.CommandBars("Menu Bar").Controls("Fa&vorite").Delete
On Error GoTo 0
Set cbcNewMenu = cbMenuBar.Controls.Add _
(msoControlPopup, , , idHelp)
cbcNewMenu.Caption = "Fa&vorite"
With cbcNewMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Properties"
.OnAction = "ShowProperties"
End With
With cbcNewMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Record"
.OnAction = "RecordMacro"
End With
End Sub
Sub InsertBreak()
Selection.InsertBreak wdPageBreak
End Sub
Sub InsertTime()
Selection.InsertDateTime DateTimeFormat:="HH:mm", InsertAsField:=False, _
DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern, _
InsertAsFullWidth:=False
End Sub

Here is how it works...

The variable cbMenuBar is set to the main Word menu bar which is called "Menu Bar".

Set cbMenuBar = Application.CommandBars("Menu Bar")

I got its name by running this code...

For Each cb In Application.CommandBars
Debug.Print cb.Name
Next
...to see all the Command Bar names.

Next, we save the ID of the help mean since we will need to supply a value to the Before parameter for the Controls.Add function...

idHelp = cbMenuBar.Controls("Help").Index

Next we delete the button if it was previously added so as not to create a second, third, etc.

On Error Resume Next Application.CommandBars("Menu Bar").Controls("Fa&vorite").Delete On Error GoTo 0

Next we set the CommandBarControl variable to a new control using the Help menu's ID for the before parameter...

Set cbcNewMenu = cbMenuBar.Controls.Add(msoControlPopup, , , idHelp)

We then give the control a caption...

cbcNewMenu.Caption = "Fa&vorite"

the "&" before the "v" will let us activate the menu with ALT + v.

We then add two items to the menu...

With cbcNewMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Properties"
.OnAction = "ShowProperties"
End With
With cbcNewMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Record"
.OnAction = "RecordMacro"
End With
The two macros at the end will be run respectively when a menu item is chosen. You can write your own macros or record them, including recording the built-in menu items as was done for this tutorial.

You can also create submenus in your VBA Word menus.


This site is powered by Site Build It!. If you enjoy it, please check out the
Site Build It homepage
 to learn more and on how to build a success-guaranteed site with no technical skills.

Custom Search






Return from VBA Word Menus to "VBA Code Samples"

Return from VBA Word menus to our "Home Page"