checkboxms-wordtextfieldactivexobject

VBA needed for checking a specific check box based on text box result


Working in Word 2010, I need VBA code for a form that will check one of two ActiveX check boxes based on text set to populate into an ActiveX text field. (Male or Female) I'm a novice and have tried various variations of the code below:

Sub copyMaleFemale()
Dim ff As String
ff = CurrentFormField.Result

If ff = ("Male") Then 
ActiveDocument.FormFields("Check1").Result = Checked 
ActiveDocument.FormFields("Check2").Result = Unchecked

ElseIf ff = ("Female") Then
ActiveDocument.FormFields("Check1").Result = Checked
ActiveDocument.FormFields("Check2").Result = Unchecked

End If

End Sub

I appreciate any suggestions.


Solution

  • You're pretty close. No brackets needed around the variable values. Something to keep in mind is that the match has to be exact, so I added a section to set both checkboxes to false if the text field is anything slightly different.

    Using With/End With is always a good way to eliminate extra code and make your macro run just a little faster:

    Sub copyMaleFemale()
        Dim ff As String
        ff = ActiveDocument.FormFields("Text1").result
    
        If ff = "male" Then
            With ActiveDocument
                .FormFields("Check1").CheckBox.value = True
                .FormFields("Check2").CheckBox.value = False
            End With
        ElseIf ff = "female" Then
            With ActiveDocument
                .FormFields("Check1").CheckBox.value = True
                .FormFields("Check2").CheckBox.value = False
            End With
        Else
            With ActiveDocument
                .FormFields("Check1").CheckBox.value = False
                .FormFields("Check2").CheckBox.value = False
            End With
        End If
    End Sub