Search code examples
vbams-wordword-contentcontrol

vba cannot clear the word ContentControl content


The contentcontrol "contents cannot be edited" checkbox is unchecked, and I use code to set

LockContets = False

, but even so, there is still error "You are not allowed to edit this selection because it is protected"

the code is as follow:

Sub Test()
  Dim CC As ContentControl  
  For Each CC In ActiveDocument.ContentControls
      Debug.Print CC.Type
      Debug.Print CC.Range.Text
      CC.LockContentControl = True
      CC.LockContents = False
      CC.Range.Text = ""    <--error here


  Next CC
End Sub

why will this happen? how to solve it?


Solution

  • You cannot clear the text from Dropdown List, CheckBox, or Picture Content Controls, since they don't have an editable text property.

    Try something along the lines of:

    Sub Test()
    Dim CC As ContentControl
    For Each CC In ActiveDocument.ContentControls
      With CC
        .LockContentControl = True
        .LockContents = False
        Select Case .Type
          Case wdContentControlRichText, wdContentControlText, wdContentControlComboBox, wdContentControlDate
            .Range.Text = ""
          Case wdContentControlDropdownList
            .Type = wdContentControlText
            .Range.Text = ""
            .Type = wdContentControlDropdownList
          Case wdContentControlCheckBox: .Checked = False
          Case wdContentControlPicture: .Range.InlineShapes(1).Delete
        End Select
      End With
    Next CC
    End Sub