Programming Office Commandbars - get the ID of a CommandBarControl

The FindControl(FindControls) method of CommandBars collection/CommandBar object is the most useful and reliable way to get the reference to a CommandBarControl object. For built-in menu items and toolbar buttons, the control ID is required for a successful call to FindControl(s). The following VBA code snippet will list control IDs of all available CommandBarControl objects(i.e., menu items and toolbar buttons) in Microsoft Word:

 'retrieve IDs of all CommandBarControl objects by enumerating every CommandBar
'object in the CommandBars collection
Sub DumpBars()
PrintLine "Command bar controls", 1
Dim bar As CommandBar
For Each bar In Application.CommandBars
DumpBar bar, 2
Next
End Sub

'retrieve IDs of all CommandBarControl objects in a CommandBar object
Sub DumpBar(bar As CommandBar, level As Integer)
PrintLine "CommandBar Name: " & bar.Name, level
Dim ctl As CommandBarControl
For Each ctl In bar.Controls
DumpControl ctl, level + 1
Next
End Sub

'retrieve the ID of a CommandBarControl object. If it is a CommandBarPopup object,
'which could serve as a control container, try to enumerate all sub controls.
Sub DumpControl(ctl As CommandBarControl, level As Integer)
PrintLine vbTab & "Control Caption: " & ctl.Caption & vbTab & "ID: " & ctl.ID, level
Select Case ctl.Type
'the following control type could contain sub controls
Case msoControlPopup, msoControlGraphicPopup, msoControlButtonPopup, msoControlSplitButtonPopup, msoControlSplitButtonMRUPopup
Dim sctl As CommandBarControl, ctlPopup As CommandBarPopup
Set ctlPopup = ctl
For Each sctl In ctlPopup.Controls
DumpControl sctl, level + 1
Next
Case Else
'no sub controls
End Select
End Sub

'Word only output function. You should modify this if you are working with
'other Office products.
Sub PrintLine(line As String, level As Integer)
Selection.Paragraphs(1).OutlineLevel = level
Selection.InsertAfter Space(level * 4) & line & vbNewLine
Selection.Collapse wdCollapseEnd
End Sub

The above code works also with Excel, PowerPoint, FrontPage, etc., provided that appropriate changes are made to the "PrintLine" function for output. With minor modification (using an Explorer object instead of the application object in the "DumpBars" sub routine, e.g., Application.ActiveExplorer), it works for Microsoft Outlook as well. You can also port it to VBScript or JScript to find certain control IDs in InfoPath.