Search code examples
vbams-wordtext-formattingword-contentcontrol

Add new text to already existing text in a content control, and make the already existing text in StrikeThrough


I have a content control that already contains text. I want to add new text, and put the previous text in StrikeThrough, my code looks like this.

Sub testCCrangeModifier()
Dim CC As ContentControl
For Each CC In ActiveDocument.ContentControls
    If CC.Title = "myContentControl" And CC.Tag = "myContentControl" Then
        CC.Range.Font.StrikeThrough = True
        CC.Range.Text = ("NEWTEXT" & Chr(13) & Chr(10) & CC.Range.Text)
    End If
Next CC
End Sub

With this code, the result is:
NEWTEXT
OLDTEXT

The result should look like this
Before the macro:
OLDTEXT

After the macro:
NEWTEXT
OLDTEXT

Chr(13) & Chr(10) is the linebreak between the oldtext and newtext


Solution

    1. Your code sets the formatting before you add the text, so obviously any text that you add is going to have that formatting.
    2. Only Rich Text Content Controls can contain different formatting.

    The code below checks that CC is a rich text content control, then adds the text and removes strikethrough from the first paragraph.

    Sub testCCrangeModifier()
       Dim CC As ContentControl
       For Each CC In ActiveDocument.ContentControls
          If CC.Title = "myContentControl" And CC.Tag = "myContentControl" And CC.Type = wdContentControlRichText Then
             With CC.Range
                .Font.StrikeThrough = True
                .Text = ("NEWTEXT" & Chr(13) & Chr(10) & CC.Range.Text)
                .Paragraphs(1).Range.Font.StrikeThrough = False
             End With
          End If
       Next CC
    End Sub