I'd not change it into function, but built in looping into the procedure.
find.Execute returns true if it finds searched term
so we shall loop until nothing is found.
First I wrote it as:
Sub FindAndReplaceAllOccurences(OldText As String, NewText As String)
Dim rngStory As Range, replaceresult As Boolean
Do
replaceresult = False
For Each rngStory In ActiveDocument.StoryRanges
With rngStory.Find
.Text = OldText
.Replacement.Text = NewText
.Wrap = wdFindContinue
replaceresult = replaceresult Or .Execute(Replace:=wdReplaceAll)
End With
Next rngStory
Loop While replaceresult
End Sub
But then thought that looping inside each story will be quicker - so try also on a large document this possibly faster version:
Sub FindAndReplaceAllOccurences_Quick(OldText As String, NewText As String)
Dim rngStory As Range, replaceresult As Boolean
For Each rngStory In ActiveDocument.StoryRanges
Do
replaceresult = False
With rngStory.Find
.Text = OldText
.Replacement.Text = NewText
.Wrap = wdFindContinue
replaceresult = replaceresult Or .Execute(Replace:=wdReplaceAll)
End With
Loop While replaceresult
Next rngStory
End Sub
Bookmarks