Search code examples
vbams-wordactivex

Can you use the name of a Check-box to access its value?


I am currently working on a Word document with ActiveX check-boxes.

You can use the following line of code to access a check-box :

ActiveDocument.InlineShapes(n).OLEFormat.Object

where n is an integer representing the position of that check-box in the document. Unfortunately for me, if any check-box or option button is added before a check-box, the position of that check-box change, thus a given n can point to a different check-box.

My question : is there a way to replace the n with the name (or something else as long as it cannot be changed by adding a new check-box) of the check-box ?

Thank you in advance.


Solution

  • It is possible to check the name of an ActiveX control, but not as an index value of a collection when the control is on the document surface. If you want to work like that I recommend using either the legacy Forms controls (same place in the Ribbon as the activeX controls list) or a Checkbox type of content control.

    ActiveX controls can be indexed by a name when the control is on a VBA UserForm, because that's the environment the controls were designed for. Word "wraps" them up in a field code and treats them as a graphic, so VBA code has to go through a couple layers of interface in order to access them on a document as an ActiveX control.

    The following code demonstrates how to address an ActiveX control by its name.

    • Loop through the InlineShapes collection
    • Check whether the type is an ActiveX control
    • Check whether it's a checkbox
    • Check the name property

    Code:

    Sub ActiveXControlByName()
        Dim ils As Word.InlineShape
        Dim cb As MSForms.CheckBox
    
        For Each ils In ActiveDocument.InlineShapes
            If ils.Type = wdInlineShapeOLEControlObject Then
                If ils.OleFormat.ClassType = "Forms.CheckBox.1" Then
                    Set cb = ils.OleFormat.Object
                    If cb.Name = "cb2" Then
                        cb.value = False
                        Exit For
                    End If
                End If
            End If
        Next
    End Sub