Julian Popov
Julian Popov

Reputation: 17471

Word CheckBox ContentContol OnChange Event

I try to make a word document with two checkboxes where each checkbox will show/hide a part of the document with a custom style.

I plan to set value Style.Font.Hidden = True/False depending from checkbox values, but...

I found that there are 3 types of controls:

Can you tell me how to atach to onChange event of CheckBox ContentContol? I need the same behaviour like it's ActiveX CheckBox.

Upvotes: 1

Views: 4662

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25693

Content Controls do not have "onChange" events, so you can't get a content control to behave like the ActiveX checkbox in a simple manner. Similarly to form fields, the code for ContentControls fires when the control is entered/exited.

The only way to emulate "onChange" for a Content Control is to link the content control to a node in a CustomXMLPart in the document then work with the Document_ContentControlBeforeStoreUpdate event that triggers when the content of the node in the CustomXMLPart is going to be changed.

If, as your question indicates, this is too complex for your purposes you could use a MacroButton field that displays a font character (Symbol) that looks like a checkbox. Clicking the field would exchange that character for a different one, that looks checked. And the reverse again for the next click. Here's some sample code to get you started. If you don't like the checkboxes I chose, you can pick something else from Insert/Symbols/Symbol. Just change the character numbers and the font name.

By default a MacroButton field triggers on double click. You can change this to a single click when the document is opened in an AutoOpen macro.

Sub AutoOpen()
    Application.Options.ButtonFieldClicks = 1
End Sub

Sub ToggleCheckBox()
    Dim iNotChecked As Integer, iChecked As Integer
    Dim rngCheck As word.Range
    Dim sBkmName As String, sFontName as String

    iNotChecked = 111
    iChecked = 253
    sBkmName = "bkmCheck"
    sFontName = "Wingdings"
    Set rngCheck = ActiveDocument.Bookmarks(sBkmName).Range

    If Asc(rngCheck.Text) = iNotChecked Then
        rngCheck.Text = Chr(iChecked)
        ActiveDocument.Bookmarks.Add sBkmName, rngCheck
        rngCheck.Font.Name = sFontName
    ElseIf Asc(rngCheck.Text) = iChecked Then
        rngCheck.Text = Chr(iNotChecked)
        rngCheck.Font.Name = sFontName
        ActiveDocument.Bookmarks.Add sBkmName, rngCheck
    End If
End Sub

Upvotes: 4

Related Questions