Question

I'm using the following in the ThisOutlookSession of my VbaProject.OTM file to add 2 custom buttons to the new mail's Standard toolbar:

Dim outl As Object
Dim msg As Object
Set outl = CreateObject("Outlook.Application")
Set msg = outl.CreateItem(0)
msg.Display (False)

Dim objBar As Office.CommandBar
Dim objButton As Office.CommandBarButton

Set objBar = Application.ActiveWindow.CommandBars("Standard")
Set objButton = objBar.Controls.Add(msoControlButton)

With objButton
    .caption = "button1"
    .OnAction = "macro1"
    .TooltipText = "Description"
    .faceId = 487
    .Style = msoButtonIconAndCaption
    .BeginGroup = True
End With

Set objButton = objBar.Controls.Add(msoControlButton)

With objButton
    .caption = "button2"
    .OnAction = "macro2"
    .TooltipText = "Description"
    .faceId = 2525
    .Style = msoButtonIconAndCaption
    .BeginGroup = True
End With

msg.Close 1

The problem is that the buttons will be added every time Outlook starts (which is needed for the other computers I'm willing to deploy my OTM file to). Is there any way to check before adding the buttons if it already exists?

Was it helpful?

Solution

You buttons is a part of the toolbar. Hence check for the existance of the toolbar.

If IsToolbar("Standard") Then 
  '-- do something
  Else 
  '-- create tool bar and add the buttons
End If

Or try this:

For Each Contrl in Application.CommandBars("Standard").Controls
   If .Caption <> "button1" then
      '-- create it
   End If
Next Contrl

EDIT as per OP's comment:

So let's stick to the error catching... (untested code, so you may have to give it a try in your end for exact correct syntax)

Dim ctlCBarControl As CommandBarControl
On Error Resume Next    
Set ctlCBarControl = Application.CommandBars("Standard").Controls("button1")

   If Err <> 0 Then
      '-- no button exists, you may add it
      Err = 0
   Else
      '-- the button is there.. 
   End If
End if

* Reference: CommandBar Controls

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top