Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using a Word Range

Status
Not open for further replies.

KenWK

Programmer
May 25, 2001
76
US
I have a situation where I want find all the occurances of a character style (called ENR) within the text selected by the user. This will eventually be expanded to replace the text coded in that character style, but for now the code below just counts the occurances of that character style in the selection.

I'm setting MyRange to Seletion.Range and setting the find options for the range object. I expected .Wrap = wdFindStop would work as it does when searching with the Selection object and that it would stop once it found all those in the range, but it continues to loop endlessly finding the same occurances over and over again.

The code is below, any help would be greatly appreciated.

Thanks,
Ken

Code:
    Set MyRange = Selection.Range
    MyRange.Find.ClearFormatting
    MyRange.Find.Style = ActiveDocument.Styles("ENR")
    With MyRange.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    ENRCntr = 0
    MyRange.Find.Execute
    While MyRange.Find.Found
        ENRCntr = ENRCntr + 1
        MyRange.Collapse wdCollapseEnd
        MyRange.Find.Execute
    Wend
    MsgBox ENRCntr
 
Try something like:
Code:
Sub Demo()
Dim i as Long
With Selection
  With .Find
    .ClearFormatting
    .Text = ""
    .Style = "ENR"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute
  End With
  Do While .Find.Found
    i = i + 1
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Msgbox i & " ENR instances found."
End Sub

Cheers
Paul Edstein
[MS MVP - Word]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top