Search code examples
excelvbams-wordword-contentcontrol

How do you ignore earlier content control using VBA in Microsoft Word?


I have a Word template where I have a checkbox content control in the middle of the document. Once this checkbox is clicked, it triggers some commands using VBA. However, I also have plain text content control and date picker content control earlier on in the document that helps in filling out the template for the user. When these boxes are selected, I keep getting an error message saying "Run-time error 6290 - This property is only available for check box content controls".

My question - is there any way to ignore the earlier content control boxes and only run the code when the checkbox is pressed?

My code at the moment looks something like this:

Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
    If (ContentControl.Title = "Checkbox1" And ContentControl.Checked = True) Then
        *code in here*
    End If
End Sub

So you would think that the code would only get triggered once Checkbox1 is checked... but the earlier text and date fields give me an error code. Anyone know what's going on?


Solution

  • I'm not familiar with "content control" or Word VBA, but in Excel, when coding for the .OnChange event, it's important to make sure the cell passed in to the Sub is (one of) the one(s) you want to work with. I'd assume the same is true here.

    My guess is your error is on the

    ContentControl.Checked = True
    

    portion of your If statement, so give this a try:

    Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
        If (ContentControl.Title = "Checkbox1") Then
          If ContentControl.Checked = True Then
            *code in here*
          End IF
        End If
    End Sub
    

    i.e., make sure you're looking at a checkbox control before testing to see if the box is checked.

    VBA does not do conditional short-cutting, so it's going to evaluate all statements in a AND conditional even if the first one is False.