Сергей
Сергей

Reputation: 47

How can I find multiple occurences of a text inside a selection (Word VBA)

I need to change the numbering of several hundred appendixes to a document. And the numbering should have different prefixes. So I want to select a part of the document and run a macro for the selection. But I can use Find.Execute only for the whole document, not for a selection. How should the code look for my task?

When I select a part of the document and run the macro, the selection collapses and code execution continues till the end of the document instead of to the end of the selection. I tried to store the End position of selection but it gives an infinite loop.

My code

Set rngSearch = Selection.Range

    Do While rngSearch.Find.Execute(FindText:="App.№", MatchWholeWord:=True, Forward:=True) = True
        'routine to change numbering (replace text) and increment counter
        rngSearch.Collapse Direction:=wdCollapseEnd

    Loop

I also tried to loop through the document paragraphs but it was way too slow (several minutes without a result).

Upvotes: 1

Views: 484

Answers (2)

Сергей
Сергей

Reputation: 47

Cindy Meister. I guess I didn't really understand your suggestion because it leads to an infinite loop changing the same region over and over again. But I tried another way: I removed the line "rngSearch.Collapse Direction:=wdCollapseEnd" and üsed the next code:

Set originalRange = Selection.Range
endPos = originalRange.End

Set rngSearch = originalRange.Duplicate
With rngSearch.Find
    Do While .Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
        With rngSearch
        rngSearch.Select
        startPos = rngSearch.End

        'routine to change numbers and increment counter

        rngSearch.Select
        rngSearch.Start = startPos
        rngSearch.End = endPos
        End With
    Loop
End With

This code works well. Could you comment if it is ok?

Upvotes: 0

Cindy Meister
Cindy Meister

Reputation: 25663

The approach I use is to work with two Range objects: one for the selected text, one for the actual search. For each pass through the loop, after collapsing the search range it's set to the end point of the selection range.

In order to make "copies" of a Range use the Duplicate property.

Sub FindOnlyInSelection()
    Dim rngSel As Word.Range
    Dim rngSearch As Word.Range

    Set rngSel = Selection.Range
    Set rngSearch = rngSel.Duplicate

    Do While rngSearch.Find.Execute(findText:="App.?", MatchWholeWord:=True, Forward:=True) = True
        'routine to change numbering (replace text) and increment counter
        rngSearch.Collapse Direction:=wdCollapseEnd
        rngSearch.End = rngSel.End
    Loop
End Sub

Upvotes: 1

Related Questions