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
(CountIt) within in (within the selected text).
I wrote this but it doesn't work!
Thanks

Sub Inizio2()
CountClass = 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:="CountIt", Format:=False,
MatchCase:=False, MatchWholeWord:=True) = True
CountClass = CountClass + 1
Loop
End With
End Sub
 
D

Doug Robbins - Word MVP

Use:

Dim myrange As Range
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")
MsgBox "There are " & myrange.Words.Count - 2 & " words 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