Search code examples
vbams-wordtogglebuttonribbonx

How do I make a ribbon toggle button which is pressed on document open behave properly when it is first toggled?


I am trying to create a toggle button in Word's ribbon that can control the document's track formatting setting, which determines whether or not formatting changes such as bold and italic are tracked with tracked changes. This setting has a UI in the Windows version of Word but not in the Mac, so I'm trying to use a macro to expose it.

The trouble is that although the button is, correctly, 'down' when a new document opens (because track formatting is on by default), the first time I press it, the button goes 'up' but formatting is still tracked. Thereafter, it toggles in opposition to the button state (i.e. off when the button is 'down', on when the button is 'up').

I've got the length of creating a button in the ribbon XML as follows:

<toggleButton id="ToggleTrackFormatting" label="Track formatting" screentip="Should formatting changes be tracked when Track Changes is on?" getPressed="GetTrackFormattingButtonPressed" onAction="ToggleTrackFormattingButton"/>

The callbacks are like this:

'Callback for ToggleTrackFormatting onAction
Sub ToggleTrackFormattingButton(control As IRibbonControl, pressed As Boolean)
        Select Case pressed
    Case True
        TurnOffTrackFormattingOptions
    Case False
        TurnOnTrackFormattingOptions
    End Select
End Sub

'Callback for ToggleTrackFormatting getPressed
Sub GetTrackFormattingButtonPressed(control As IRibbonControl, ByRef returnedVal)
    returnedVal = ActiveDocument.TrackFormatting
End Sub

and

Sub TurnOnTrackFormattingOptions()
ActiveDocument.TrackFormatting = True
End Sub

Sub TurnOffTrackFormattingOptions()
ActiveDocument.TrackFormatting = False
End Sub

Have I done something wrong with the getPressed callback, or is there something else going on?


Solution

  • If you are simply toggling the state of TrackFormatting there is no need to examine the pressed state of your toggle button.

    Simply change your OnAction callback to:

    'Callback for ToggleTrackFormatting onAction
    Sub ToggleTrackFormattingButton(control As IRibbonControl, pressed As Boolean)
        ActiveDocument.TrackFormatting = Not ActiveDocument.TrackFormatting
    End Sub
    

    If you haven't already done so you will also need to add an event handler for the DocumentChange event and invalidate either the ribbon or the toggle button so that it shows the correct pressed state for the active document.

    For your getPressed callback you also need to handle the case that no document is open as your existing code will generate an error.