Commandbar button multiple installs

D

David

OK I nabbed this code from this board and tweaked it to suit my needs.

This is a document, not a template.

It correctly installs the button in the document only once as the code
indicates. Multiple runs of the code only install one button.

The problem is when I close the document, and I'm back to a blank Word
desktop, there are as many buttons on the bar as times I've run the
code.

I need the button to be available in the document only.

Code is in Module 1.

Thanks,
David

Public Sub AutoOpen()
'Check for Protect
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect
End If
'install the button
Dim ctl As Office.CommandBarControl 'where the button will be
Dim ctlButton As Office.CommandBarButton
'before adding the button, verify if it is already installed ...
Set ctl = CommandBars("standard").Controls(CommandBars("standard").Controls.Count)
If ctl.Caption <> "Run TTD" Then
Set ctlButton = CommandBars("Standard").Controls.Add
With ctlButton
.Caption = "Run TTD"
.TooltipText = "Click to create Time Tracking Document"
.OnAction = "Main" 'the procedure to be call when a click
....
.Style = msoButtonCaption
End With
Else
'we are adding nothing to the toolBar, it is already here
End If

'Protect doc
ActiveDocument.Protect (wdAllowOnlyFormFields)
Main
End Sub
 
P

Peter

I can't exactly replicate the "as many buttons in the bar as times I've run the code" situation, but the reason the button sticks around after you close the document is because when you add the button to the commandbar, you're actually adding it to the Normal template, not to the document.
Add this line of code just prior to your Dim statements:
CustomizationContext = ActiveDocument
That tells the code to add the button to the document, not the normal template.

-Peter
 
D

David

Peter said:
... but the reason the button sticks around after
you close the document is because when you add the button to the
commandbar, you're actually adding it to the Normal template, not to the
document.
Add this line of code just prior to your Dim statements:
CustomizationContext = ActiveDocument
That tells the code to add the button to the document, not the normal
template.

-Peter

Ahh... I always forget about the scope of things.

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top