Creating Access menus and toolbars in code


Q: How can I create a menu bar or a toolbar dynamically in Access?

A. You can either use Access macros or Access VBA.

The following code shows how it can be done in VBA. A reference to the Microsoft Office Object Library is required

Sub AddMenuBar(strMenu As String)
'This procedure adds a menu bar, which replaces the standard menu bar

  Dim cbar As Office.CommandBar

  'Add the menu bar
 
Set cbar = CommandBars.Add(strMenu, , True, True)

  cbar.Visible = True 'Show it

End Sub


Sub AddTopMenu(strMenu As String, strCaption As String)
'This procedure adds a top menu on the strMenu menu bar

  Dim cctl As Office.CommandBarControl

  'Add the top menu
 
Set cctl = CommandBars(strMenu).Controls.Add(msoControlPopup)

  cctl.Caption = strCaption     'Give it a caption

End Sub

Sub AddMenu(strMenu As String, strTopCaption As String, strCaption As String, strProc As String)
'This procedure adds a menu under strTopCaption

  Dim cctl As Office.CommandBarControl

  'Add the menu
 
Set cctl = CommandBars(strMenu).Controls(strTopCaption).Controls.Add(msoControlButton)

  cctl.Caption = strCaption      'Give it a caption
  cctl.OnAction = strProc        'Refer it to a procedure

End Sub

Sub AddToolBar(strToolbar As String)
'This procedure adds a tool bar at the top of the window

  Dim cbar As Office.CommandBar

  'Add the toolbar
 
Set cbar = CommandBars.Add(strToolbar, msoBarTop, , True)

  cbar.Visible = True 'Show it

End Sub

Sub AddButton(strToolbar As String, intImage As Integer, strProc As String)
'This procedure adds a button on strToolbar

  Dim cctl As Office.CommandBarControl

  'Add the button
 
Set cctl = CommandBars(strToolbar).Controls.Add(msoControlButton)

  cctl.FaceId = intImage      'Give it an image
  cctl.OnAction = strProc     'Refer it to a procedure

End Sub

Sub SubExit()
'This is the procedure started by the menu/toolbar button
'It performs Access's normal exit function

 DoCmd.RunCommand acCmdExit

End Sub

Sub Initialize()
'The first three lines of this procedure shows how the menu bar is added,
'the next two lines how a toolbar is added

  AddMenuBar "MyMenu"
  AddTopMenu "MyMenu", "Arkiv"
  AddMenu "MyMenu", "Arkiv", "Exit", "SubExit"

  AddToolBar "MyToolbar"
  AddButton "MyToolbar", 59, "SubExit"   '59 is the happy face icon

End Sub