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

Philip Vasey 0 Reputation points
2023-03-18T13:57:18.9+00:00

Find.Execute Error

Word
Word
A family of Microsoft word processing software products for creating web, email, and print documents.
673 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,532 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Doug Robbins - MVP - Office Apps and Services 166 Reputation points MVP
    2023-03-19T04:44:06.2233333+00:00

    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
            Loop
        End With
    End With
            
    If boolfound = True Then
        MsgBox "The text that you were searching for exists within the selected range."
    Else
        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,081 Reputation points MVP
    2023-03-18T16:57:04.4466667+00:00

    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
    2023-04-17T17:48:50.4966667+00:00

    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