Tuesday, August 5, 2008

Accessing the Office Ribbon from VBA

Yesterday I received this email from a co-worker (who shall remain anonymous):

1. Open an instance of Word 2007 to find the msoId of the button you’d like to press. You can find this by going to Office Button Word Options Customize to view a list of commands which correspond to buttons.

2. Hover over the name of the command and you’ll see a tooltip; for example, the tooltip for the Save command when selected from the “Popular Commands” list says “Popular Commands Save (FileSave)”. The part in parentheses is the msoId. (Note: You may have to select the name of a tab in the “Choose commands from:” list box to find the button you’re looking for.)

3. In your code, call Word.Application.CommandBars.ExecuteMso with the msoId and you can invoke the button.

Note: The steps above also apply to Excel.

Code Example to demonstrate how to press FileSave in Word 2007

[VBA]
Sub PressThisRibbonBarButton()
On Error Resume Next
If Word.Application.Documents.Count = 0 Then Exit Sub
' Press the Save button Word.Application.CommandBars.ExecuteMso "FileSave"
End Sub


I haven’t worked with the Office 2007 API yet, but I thought this seemed like a good tip that was worth posting here. However, today I was researching something else, and discovered a post on the Interwoven Devnet forums by someone named jny. It looks like the previously mentioned co-worker was trying to pull a fast one, and borrow jny’s post. Anyway, I still thought this was helpful, so thanks to jny from the Interwoven forums for the helpful tip.

No comments: