How to convert a search string to a field?

0

I have a document with many occurrences of INCLUDEPICTURE "imagename.png". Instead of having to select the text and press Ctrl+F9, I want to do it automatically.

Is it possible to convert the pattern INCLUDEPICTURE*png into a field?

jinawee

Posted 2019-07-05T12:41:34.493

Reputation: 103

Did @Traveler 's Answer actually answer your question? If so, can you mark the Answer as an Answer? – None – 2019-12-18T21:56:47.630

Answers

1

It's not possible with Word's Search&Replace because ^d (find field) cannot be used together with wildcards, but this macro will do it:

Sub ConvertToField()
    Do
        With Selection.Find
            .Text = "INCLUDEPICTURE ""*.png"""
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = True
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute
        If Selection.Find.Found = False Then Exit Do

        Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
        Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
        Selection.MoveRight Unit:=wdWord, Count:=1

    Loop While True
End Sub
Sub ConvertToText()
    Do
        With Selection.Find
            .Text = "^d"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute
        If Selection.Find.Found = False Then Exit Do

        If Selection Like "* INCLUDEPICTURE *.png*" Then
            Selection = Mid(Selection, 3, Len(Selection) - 2 - 2)
            Selection.Move wdCharacter, 1
        End If
    Loop While True
End Sub

Traveler

Posted 2019-07-05T12:41:34.493

Reputation: 182