count a string within a selected text

R

RuGio

Hi, I would like to know a routine to select a text (from a word
(Summer) to another word (Winter)) and to count a specific word
(for example "Sun" ) within in (within the selected text).
I wrote this but it doesn't work! HELP!
Thanks


Sub CountSun()
Counter = 0
Selection.Find.ClearFormatting
With Selection.Find
.Text = "Summer "
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
Selection.StartOf Unit:=wdWord 'Selection.EndOf Unit:=wdWord
Selection.Extend
Selection.Find.ClearFormatting
With Selection.Find
.Text = "Winter:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
End With
Selection.Find.Execute
With Selection.Find
Do While .Execute(FindText:="Sun", Format:=False,
MatchCase:=False, MatchWholeWord:=True) = True
Counter = Counter + 1
Loop
End With
End Sub
 
D

Doug Robbins - Word MVP

You need to learn from the answer that you were given to your other
question:

For this one, use:

Dim myrange As Range
Dim i As Long
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = "Summer "
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute
Set myrange = Selection.Range
myrange.End = ActiveDocument.Range.End
myrange.End = myrange.Start + InStr(myrange, "Winter")
With myrange.Find
Do While .Execute(FindText:="Sun", MatchCase:=True,
MatchWildcards:=False, MatchWholeWord:=True, Wrap:=wordfindstop) = True
i = i + 1
Loop
End With
MsgBox "The word Sun appears " & i & " times between Summer and Winter."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top