Search code examples
vbacheckboxms-wordexpandword-contentcontrol

Word VBA - Expand a header if a certain checkbox is ticked?


Used VB for Excel, but new to VB for Word. I'm not sure how to expand a heading if a certain checkbox is marked true. This is the code I currently have and I get a run time error saying that the requested member of the collection does not exist, but I have named the CheckBox in the properties window of the control. I am using Version 1808 (Build 10730.20262 Click-to-Run) of Microsoft Word.

Sub Macro1()

If ActiveDocument.FormFields("Licensing_1").CheckBox.Value = True Then
    Do Until Selection.Find.Found = False
        If Selection.Text Like "Licensing Discovery Questions" Then
        Selection.Find.Style = ActiveDocument.Styles("Heading 1")
        Selection.Find.Execute
            Else: Selection.Paragraphs(1).CollapsedState = True
        Selection.Find.Style = ActiveDocument.Styles("Heading 1")
        Selection.Find.Execute
    End If
Loop
End If

End Sub

Solution

  • Unlike form fields, multiple Word content controls can have the same designation (name - the actual term is Title). For this reason, it's not possible to use the string as an index value - it's not guaranteed to be unique.

    For this reason, it's necessary to use the method SelectContentControlsByTitle (or SelectContentControlsByTag) to pick up a content control object. The method returns a Collection of content controls - all that have the same Title or Tag. (Note: these are case-sensitive!).

    If the code should work with all of these content controls, then use a For Each loop with the collection.

    If the code should work with only one content control (the first, for example), this can be specified using the ContentControls.Item property.

    On the assumption there is only one checkbox in the document that has the designation "Licensing_1":

    Sub CheckBox_CC()
        Dim ccCheckBox As Word.ContentControl
        Dim doc As Word.Document
    
        Set doc = ActiveDocument
        Set ccCheckBox = doc.SelectContentControlsByTitle("Licensing_1").Item(1)
    
        If ccCheckBox.Checked Then
            'Do things here
        End If
    End Sub