Why does Range.Find.Execute yield a range that is outside the original search range

Philip Vasey 0 Reputation points

Find.Execute Error

A family of Microsoft word processing software products for creating web, email, and print documents.
654 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,457 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Doug Robbins - MVP - Office Apps and Services 166 Reputation points MVP

    Using VBA, you could use

    Dim rngsearch As Range
    Dim boolfound As Boolean
    Set rngsearch = Selection.Range
    boolfound = False
    With Selection
        .HomeKey wdStory
        With .Find
            Do While .Execute(FindText:="coordinated", Forward:=True, _
            MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True
                If Selection.Range.Start >= rngsearch.Start And Selection.Range.End <= rngsearch.End Then
                    boolfound = True
                End If
                Selection.Collapse wdCollapseEnd
        End With
    End With
    If boolfound = True Then
        MsgBox "The text that you were searching for exists within the selected range."
        MsgBox "The text that you were searching for does not exist within the selected range."
    End If
    1 person found this answer helpful.
    0 comments No comments

  2. Stefan Blom 2,061 Reputation points MVP

    I believe that the explanation is that executing a Find will redefine the Range for the search. A common workaround is to add a check to verify that the search is still being done in the originally defined Range.

    Experienced VBA coders such @Doug Robbins - MVP and @Jay Freedman may offer more detailed suggestions.

  3. Philip Vasey 0 Reputation points

    I have found a workaround to this ludicrous MS Word behaviour: If searching forward in the range [A,B] and the text is found before A, then iteratively search backward in the range [A,B] for the last occurrence of the text. If searching backward in the range [A,B] and the text is found after B, then iteratively search forward in the range [A,B] for the last occurrence of the text. Looking at the data produced, searching forward (backward) in the range [A,B] finds text before A (after B) when it is closer than any occurrence actually within the search range itself.

    0 comments No comments