code etc.

Custom Ribbons for MS Word

Office 2007 introduced Word documents that are actually nothing more than zipped (compressed) XML. In fact, you can open a docx or docm file like any other zip archive in Windows simply by changing the extension to zip. Modifying the ribbon is as simple as editing a few files within the archive.

The steps below will work for the other Office file types as well.

To register a custom ribbon, edit \_rels\.rels, which acts like a manifest. The .rels file in a brand-new Word documents looks like this on my system:

In this example, the ribbon customizations live in a file at custom/myRibbon.xml.

Here is a sample custom ribbon, with some commentary to help you understand what’s going on:

<?xml version="1.0" encoding="utf-8" ?><customUIxmlns="http://schemas.microsoft.com/office/2006/01/customui"><ribbonstartFromScratch="true"><!-- remove the default ribbon entirely --><tabs><!-- you can have multiple tabs, but there is only one tab in this example --><tabid="CustomTab"label="My Tab"><groupid="SimpleControls"label="This Labels the Group"><!-- the tab, group, and button label values are presented to the user --><buttonidMso="FileSaveAs"imageMso="FileSaveAs"size="large"label="Save As"/><!-- call built-in actions with idMso... --><buttonidMso="FilePrint"imageMso="FilePrint"size="large"label="Print"/><!-- use built-in icons with imageMso... --><buttonid="btnInsertText"imageMso="WordArtEditTextClassic"size="large"label="Insert Text"onAction="subInsertText"/><!-- call your own functions with onAction... --></group></tab></tabs></ribbon></customUI>

To call your own function, like with the last button in the example above, the file must be saved as a macro-enabled document. Those use file extensions that end in m rather than x (dotm, dotx).

Here is some sample code for a message box that will be displayed whenever the final button is pressed:

You’ll notice that the subroutine has a ribbon control object passed in, which contains, among other things, the id from the ribbon XML file. This allows you to use a single function and switch to handle multiple related buttons. This can be a helpful way to organize your code.