PDA

View Full Version : Solved: Find Nth Instance of a Word in Word



Anne Troy
04-10-2005, 09:29 PM
I want to find the 10th instance of the word "fox" in the attached document. Can someone make my code loop and then highlight the 10th one and stop searching? The tenth one is clearly underlined and bolded in my sample.

Thanks a bunch!

brettdj
04-10-2005, 10:55 PM
no loop needed


Sub DreamboatFox()
Dim Regex, RegM
Dim Mystr As String
Mystr = "fox"
Set Regex = CreateObject("vbscript.regexp")
With Regex
.Pattern = Mystr
.Global = True
End With
Set RegM = Regex.Execute(ActiveDocument.Content)
If RegM.Count > 9 Then
ActiveDocument.Content.Characters(RegM(9).firstindex + 1).Select
With Selection
.MoveRight Unit:=wdCharacter, Count:=Len(Mystr) - 1, Extend:=wdExtend
.Font.Bold = True
.Font.Underline = True
End With
End If
End Sub

Anne Troy
04-10-2005, 11:01 PM
GREAT!! Now go post it "over there". LOL!!

http://www.experts-exchange.com/Applications/MS_Office/Q_21382123.html

Jacob Hilderbrand
04-10-2005, 11:36 PM
Better yet, post it to the Kb and post a link "Over There". :)

Anne Troy
04-10-2005, 11:40 PM
There's already a link over there to this thread. LOL!!
But that was my whole purpose. Sounded like a nice KB entry to me.

brettdj
04-10-2005, 11:53 PM
LOL :)

MOS MASTER
04-11-2005, 10:57 AM
no loop needed
Why?? :( (I love looping)

No really, regular expressions is the way to go.
So brilliant coding! :clap:

For all the other "Loop lovers" on off the many other possibillities but now with a loop (Just "Yoinking" you...learned it today..)
Sub GetTheFox()
MarkIt "fox"
End Sub
Sub MarkIt(sFind As String)
Dim oWord As Word.Range
Dim iCnt As Integer
For Each oWord In ActiveDocument.Range.Words
If Trim(oWord.Text) = sFind Then
iCnt = iCnt + 1
If iCnt = 10 Then
With ActiveDocument.Range(Start:=oWord.Start, End:=oWord.End - 1)
.Bold = True
.Underline = True
End With
Exit For
End If
End If
Next oWord
End Sub

See Yah!