Search for part of a word, then replace the whole word

30 Views Asked by At

I am trying to search for a certain part of a word, then replace the whole word.

Imaginary example:
The document contains two words: "when, where"

I want to search for "wh" then, change the whole word to a space or delete it.

Real example:

%%hyperlink%%312
%%hyperlink%2210

I want to search for any sentence or word that contains %%hyperlink%%

then replace the whole thing, for example, replace or delete "%%hyperlink%%312 %%hyperlink%2210"

AutoExec Hyper
Dim rng As Word.Range
Dim SearchString As String

Set rng = ActiveDocument.Content
SearchString = "sa"
With rng.Find
    Do While .Execute(findText:=SearchString, Forward:=True) = True
      rng.MoveEndUntil (" ")
      Selection.Expand Unit:=wdWord
      MsgBox rng.Text
      rng.Collapse wdCollapseEnd
    Loop
End With
End Sub
1

There are 1 best solutions below

0
macropod On

You should learn how to use wildcards in Find/Replace. For example, to delete all the %%hyperlink%% strings:

Sub Demo()
Application.ScreenUpdating = False
  With ActiveDocument.Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = " %%hyperlink%%[! ]@>"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchWildcards = True
    .Execute Replace:=wdReplaceAll
  End With
Application.ScreenUpdating = True
End Sub