Search code examples
vbams-wordmailmergeword-contentcontrol

How to find/replace a symbol with a check box control in Word


I have mail merge field in my Word 2010 document that contains a check box control that is checked or not depending on the content from the input list.

{IF NEW = "NEW" "☒" "☐"} where those boxes are actually check box controls

However, after the mail merge is complete, the check box control is replaced with a symbol for the checked or unchecked box, as appropriate. As a result, one can no longer switch from checked to unchecked in the final document as you would for a check box control.

A similar question was asked here but was unresolved (one response with a solution does not work for me).

I am looking for a simple way to find the checked or unchecked symbol in the output document and replace it with a check box document control in the appropriate state.

I'm not big on programming, but if you could point me in the right direction, I'll try my best. I have played around with VB Macros in the past (very amateur), so I tried that again and got this far as a "proof of concept":

Sub Checkbox()
' ChrW(9744) is unchecked box; 9746 is checked box
    Selection.HomeKey Unit:=wdStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = ChrW(9744)
        .Replacement.Text = ChrW(9746)
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.HomeKey Unit:=wdStory
End Sub

I also found out the way to add a checkbox control:

Selection.Range.ContentControls.Add (wdContentControlCheckBox)

But I haven't figured out how to marry that last piece of code into the 'replace' line, nor how to define the checkbox as checked or not, based on the search.

Thanks for the help.


Solution

  • You can do the following:

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Do
      With Selection.Find
        .Text = ChrW(9744) ' ChrW(9746)
        .Forward = True
        .Wrap = wdFindStop 'wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
      End With
      If Selection.Find.Execute = False Then Exit Do
      ' This adds the checkbox at the selected position
      Set f = ActiveDocument.FormFields.Add(Range:=Selection.Range, _
                                            Type:=wdFieldFormCheckBox)      
      'f.CheckBox.Value = True ' Add this for checked checkboxes
    Loop