Search code examples
c#checkboxautomationms-wordbookmarks

Formfields.BookMarks.get_Item().Checkbox.Value doesn't work (automation word)


I'm trying unsuccessfully to change the value of a word Checkbox (from developer tab) via automation in C#. I've tried different ways but the only one I always find when I search on internet is :

find the name of the checkbox by clicking on properties of the checkbox when you are in developer mode

object oCheckbox = "Checkbox_name"

document_name.FormFields.get_Item(ref oCheckbox).CheckBox.Value = true/false;

But whenever I execute the code I get the following error (the request member of the collection does not exist) who means that there's no checkbox named "Checkbox_name" in my document if I understand correctly.

I also tried to Bookmark the checkbox with the same name and to execute :

document_name.BookMarks.get_Item(ref oCheckbox).CheckBox.Value but it doesn't work too...


Solution

  • If you inserted a checkbox by clicking on the checkbox shown in the developer tab, then I assume you're using Word 2007 or later.

    And, if that's the case, then what you inserted was not a form field, but a content control. Therefore if you enter the following into the immediate window in the VBA editor:

    ?ActiveDocument.Content.FormFields.Count
    

    ...it will print "0". Whereas if you try:

    ?ActiveDocument.Content.ContentControls.Count
    

    ...it should print some number greater than zero, depending on how many of these you inserted.

    To insert an old-style form-field checkbox, click the folder-with-tools icon right next to the checkbox icon - this drops down more types of controls, including "Legacy Forms" and "ActiveX Controls". There is a checkbox in each group, but it's the first group ("Legacy Forms") that will create the checkbox that shows up in the FormFields collection.

    I would suggest using the content control if possible, since the old-style form fields may not be supported forever.