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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to calculate the appearance frequency of a word in an article? 1

Status
Not open for further replies.

olin

Technical User
Jun 6, 2003
67
US

I want to make a statistics of the times of the appearance of some certain words in the MS Word article. How to do this work?

Thanks a lot!
 
You can use the Replace function (You just replace the word with itself), and increment each time you find it.
This little code contains all search words in the array "wds", the respective occurences in the array "occs":

Code:
Sub count_occurences()
Dim wds As Variant, occs As Variant, i As Integer

wds = Array("Can", "you", "dig", "this")
occs = Array(0, 0, 0, 0)

For i = 0 To UBound(wds)
    Selection.HomeKey unit:=wdStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = wds(i)
        .Replacement.Text = wds(i)
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Do
        Selection.Find.Execute Replace:=wdReplaceOne
        Selection.MoveRight unit:=wdCharacter, Count:=1
        If Selection.Find.Found Then occs(i) = CInt(occs(i) + 1)
    Loop Until Not Selection.Find.Found
Next i

End Sub

Now, occs(0) contains the number of occurences for the word "can"..
;-)

Is this what you're looking for?

Cheers,
Andy

[blue]The last voice we will hear before the world explodes will be that of an expert saying:
"This is technically impossible!" - Sir Peter Ustinov[/blue]
andreas.galambos@bowneglobal.de
HP:
 
Hi Olin,

You can also use the following code to loop through all words in the document and count all matching ocurrences.

Code:
sub count_match()
counter = 0

For Each wd In ActiveDocument.Words
If wd = "Your word" Then
counter = counter + 1
End If
Next
MsgBox counter
end sub

HTH

Matt
[rockband]
 
In principle yes, Matt.
But cycling through each word in the document for a number of words?
For a large document and several words, this could take ages - especially if the document contains tables.

Ever tried to run a compare macro on a Word table of several hundreds of entries? Makes your day - in the true sense of the meaning... :)

But: lean code indeed... [thumbsup2]
 
MakeItSo,

Agreed your code is much quicker. Star for you as I will use this in the future.



Matt
[rockband]
 
thanks you both a lot! They're really helpful!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top