Use Outlook ribbon button name as string in a macro

304 Views Asked by At

I'm trying to get the name of a clicked button on the "Developer" Tab on the ribbon to use as a string in a macro in Outlook version 2212 with M365.

Sub ButtonNameDisplay()
Dim ButtonText As String
ButtonText = ActiveSheet.Shapes(Application.Caller).Name
MsgBox (ButtonText)
End Sub

However, ActiveSheet is only for Excel. And I couldn't get the CommandBarButton.Caption property to work either

ButtonText = Application.ActiveInspector.CommandBarButton.Caption

What can one set the ButtonText string value to so the message box displays the button name [TestButtonName] when clicked?

1

There are 1 best solutions below

0
On

Typically the ribbon button instance (IRibbonControl) is passed as a parameter where you could get all the required information about the control (at least such as Id).

In the following code:

ButtonText = Application.ActiveInspector.CommandBarButton.Caption

The Inspector class doesn't provide the CommandBarButton property. To find the required control you need to use the CommandBars.FindControls method which gets the CommandBarControls collection that fits the specified criteria. You could use the IRibbonControl.Id value to find the control and get the caption property.

There are other techniques for getting information about the UI such as Accessibility API, but that is too complex for VBA macros.

Anyway, command bars were deprecated and shouldn't be used any longer in Office add-ins for customizing the UI. Instead, the Fluent UI is used for creating a custom UI. Unfortunately Outlook doesn't allow customizing the UI from VBA macros like other host applications do, the best what you could do is to customize the QAT or move a button to the tab manually with a macro assigned to it. Read more about the Fluent UI (aka Ribbon UI) in the following articles: