Search code examples
vbams-word

How do I get Range.Find to stop at the end of the range?


After defining a range in Word, I'm trying to delete all occurrences of a string within that range. However, the Find function instead continues to the end of the document.

I'll illustrate the problem with a toy example. I set up a Word document containing the following text:

start of range
    a b c d e f
end of range

a b c d e f

And then use this code:

Sub test()

    Dim r As Range
    
    Set r = ThisDocument.Content
    
    'Limit the range to between the start and end flags
    r.Find.Execute findtext:="start of range*end of range"
    
    'Delete all instances of "b". Intended to work only within the flags
    Do While r.Find.Execute(findtext:="b", replacewith:="", Wrap:=wdFindStop)
    Loop

End Sub

I want this code to only delete the b inside the flags, but it ends up deleting both despite explicitly defining the Wrap parameter to be wdFindStop. How can I make the Find function stop at the end of r?


Solution

    • .Execute Replace:=wdReplaceAll replace all instances without looping

    Microsoft documentation:

    Find.Wrap property (Word)

    Find.Execute method (Word)

    Sub DelWords()
        Dim searchRng As Range, iEnd As Long
        iEnd = ActiveDocument.Paragraphs(4).Range.End
        With ActiveDocument.Range(0, iEnd).Find
            .ClearFormatting
            .Text = "b"
            .Forward = True
            .Wrap = wdFindStop '**
            With .Replacement
                .Text = ""
                .ClearFormatting
            End With
            .Execute Replace:=wdReplaceAll
        End With
        Application.ScreenUpdating = True
    End Sub
    

    enter image description here