Amin Ya
Amin Ya

Reputation: 1938

Select the result of replacement - Word Macro

I want to get and select the result of a find and replacement macro and do some operations on it.

Say, this is the text: ‎\[abc\]‎, I want to convert it to abc and then select abc.

Here is the code:

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "(\\\[)(*)(\\\])"
        .Replacement.Text = "\2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.Cut

Here in the last line, Selection.Cut gives an error that the Selection is empty. I want to select the output of the replacement and Cut it.

From my repository Amin MSWord VBA macros

Upvotes: 1

Views: 316

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

wdReplaceAll as the Replacement "target" doesn't jump to individual "hits", which is why the Selection is not picking up anything.

Use wdReplaceOne, instead, and the Selection (or Range object, if that is used) will move to the found content.

You might want to test whether something was actually found before issuing the .Cut command as that could have unexpected consequences if nothing is found (delete content at the point where the macro was initiated). For example:

Sub FindReplaceAndCut()
    Dim found As Boolean

    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "(\\\[)(*)(\\\])"
        .Replacement.Text = "\2"
        .Forward = True
        .wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    found = Selection.Find.Execute(Replace:=wdReplaceOne)
    If found Then
        Selection.Cut
    End If
End Sub

Upvotes: 1

Related Questions