Reputation: 23
I created a Word template with a custom XML ribbon, and I am making it to be the default when creating documents from this template.
I have in the code:
Public myRibbon
Sub Onload(ribbon As IRibbonUI)
'Creates a ribbon instance for use in this project'
Set myRibbon = ribbon
myRibbon.ActivateTab ("CustomTab1")
End Sub
This works great for the first document created from template, however if there is a document open and I start a new one, the new one does not open on the selected tab. I have tried adding:
Sub AutoNew()
myRibbon.ActivateTab ("CustomTab1")
End Sub
And I have tried this:
Sub AutoNew()
myRibbon.Invalidate
myRibbon.ActivateTab ("CustomTab1")
End Sub
But neither works. How can I fix it?
Upvotes: 0
Views: 1245
Reputation: 3391
I've found creating a ribbon programmatically to be more trouble that it’s worth. Instead I use the XML approach. There are several free editors available, and one is called Office Custom UI Editor.
There are many tutorials online, so I won't give one here. Just search for 'custom ribbon xml' or similar.
Here is some basic XML code for creating a custom tab:
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="customTab" label="CustomTab1">
<group id="grpCustomTab" label="CustomGroup1">
<button id="btnCustomButton" label="A custom button" imageMso=" ShapeSmileyFace" size="large" onAction="ACallBack" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
The important things here are onAction="ACallBack"
and buttonID
. The onAction parameter is the sub that will be called when the button is clicked. Every button should have the same onAction sub, with this special signature:
Sub ACallBack(control As IRibbonControl)
You can call the sub anything valid, but it must have the IRibbonControl
parameter. The buttonID is what you use to then call the right sub. Let’s say you had buttons with IDs ID1, ID2 and ID3. Your code might look like:
Sub ACallBack(control As IRibbonControl)
Application.Run CStr(control.ID)
End Sub
Sub ID1
MsgBox "This is sub 1"
End Sub
Sub ID2
MsgBox "This is sub 2"
End Sub
Sub ID3
MsgBox "This is sub 3"
End Sub
Using this approach all documents based off the template will automatically display your custom ribbon.
Upvotes: 0
Reputation: 7860
If you already have a document based on this template open then the ribbon in that template has already loaded, which is why the OnLoad event does not fire.
There isn't a reliable method of activating a tab via code.
However, there may be a solution to this that does not require any code. Observe which tab is activated when a new document based on your template is created.
If it is the Home tab all you need to do to have your tab activated instead is place your tab before the Home tab. You do this by editing the ribbon xml to look something like this:
<tab id="tabCustom" insertBeforeMso="TabHome" label="My Custom Tab">
If it isn't the Home tab, you're out of luck!
Upvotes: 1