0
votes

i have many documents with variable-words inside brackets like this: [my_word] My code already finds all those words and i save them as String.

Now I need a function to replace this String with a ContentControl Element. Is this possible? Because I first need to generate an element, then change the text inside and the tag of it, both with [my_word].
Any help is appreciated.

1
docs.microsoft.com/en-us/office/vba/word/concepts/… has code examples for adding content controls - Tim Williams
Please show us the (minimal) code you use to find these terms. With reservations - depending on the code you're using - the answer is: Yes, it should be possible. But to be more specific we do need to see code. - Cindy Meister

1 Answers

0
votes

My Code so far looks like this (right now it is possible to replace one word at a time with a control element; I would like to replace all inside on macro. Word tells me it is not possible to replace multiple Selections, so I would have to rerun this macro mutliple times manually..)

Sub ReplaceTags()
'
' ReplaceTags Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "\<?*\>"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute
    Selection.Range.ContentControls.Add (wdContentControlText)
End Sub

EDIT: I worked on my code a little bit and found a solution to replace the text I am looking for:

Sub ReplaceTags()
'
' ReplaceTags Macro
'
'

With Selection.Find
    .ClearFormatting
    .Text = "\<?*\>"
    .Execute Forward:=True
    .MatchWildcards = True
End With

If Selection.Find.Found = True Then
    Selection.Range.ContentControls.Add (wdContentControlText)
    Selection.ParentContentControl.Tag = Selection.Text
End If

End Sub

Still I am not quite sure how to do this on the complete document without having to click "run macro" a whole lot of times

EDIT(EDIT): I solved it. In case somebody has the same problem in future:

Sub ReplaceAllTags()
'
' ReplaceAllTags Macro
'
'
For i = 0 To ActiveDocument.Words.Count
    Selection.EscapeKey
    Application.Run MacroName:="ReplaceTags"
Next
End Sub

ReplaceTags() is the same function as above.