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

Count instances of an individual word in MS Word

Status
Not open for further replies.

Speccy

MIS
May 18, 2006
5
US
Hi.

I'm trying to write some VBA code that will identify the number of an individual word instance....

i.e 'happy' is featured in the document 12 times, I'd like a function or some code that would return me '12'.

I've looked in many places and this doesn't seem like a common problem.

Thanks for anything.

Theo
 
Dim y As Integer
Dim Response

With ActiveDocument.Content.Find
Do While .Execute(FindText:="happy", Forward:=True, Format:=True, _
MatchWholeWord:=True) = True

y = y + 1
Loop
End With

Response = MsgBox(Str$(y))
 
Just with native functionality.

Find, with the the "Highlight all items found in" option checked.

Tools | Word Count ... will tell you how many instances of whatever you are searching for exist.

Unfortunately the macro recorder fails to capture the Word count menu item, so I have no idea how you might get to it via VBA.

You would think that selection.words.count would do the trick, but it doesn't. Help notes that the selection object is "unpredictable" when the selection is non-contiguous.
 
Not sure what you mean by "native functionality".
Unfortunately the macro recorder fails to capture the Word count menu item, so I have no idea how you might get to it via VBA.
The supplied code DOES precisely that with VBA.


Selection.Word.Count DOES do a word count...of the Selection. If the whole document is not selected...well...

Also note using the Selection object for a word count can be "unpredictable" - although that is not truly accurate - because the period at the end of a sentence COUNTS as a word. generally speaking you should avoid using the Selection object for generalized information. Although, of course, it may be exactly the correct object to use for specific reasons.

EXAMPLES:

This is a sentence. - selected, but NOT including period = 4 words.

This is a sentence. - selected WITH the period = 5 words.

This is a sentence. - selected with period and the paragraph mark = 6 words.

The supplied code does not use the Selection object, it uses ActiveDocument.Content. I would like to point out that:
Code:
Dim y As Integer
With ActiveDocument.Content.Find
        Do While .Execute(FindText:="happy", Forward:=True, Format:=True, _
           MatchWholeWord:=True) = True
           y = y + 1
        Loop
End With
MsgBox y
works just as well. You do not need the Variant Response, nor the Str(). A messagebox handles the display of the integer fine.

Gerry
 
mintjulep,

The important thing the macro recorder fails to record - because it can't be done with VBA - is the "highlight all items" bit.

Speccy,

This is a (relatively) common request and I'm sure I can dig out some more general purpose code if you want it, but what you have looks good for what you asked for.

Gerry,

I seem to remember having some fun doing this with Replace All and Undo a while back at VBAX - ring any bells?

Enjoy,
Tony

--------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.
Excel VBA Training and more Help at VBAExpress[
 
By "native functionally" I mean things that you can do by clicking on standard menu commands.

selection.words.count

works if the selection is contiguous

[highlight]one two three four[/highlight]

selection.word.count returns 4

but not if the selection is not contiguous

[highlight]one[/highlight] two [highlight]three[/highlight] four

selection.word.count returns 1
 
Yes, Tony.....

mintjulep, I don't know where you got the thing about having it highlighted. Having it highlighted was never mentioned.
I'm trying to write some VBA code that will identify the number of an individual word instance....
No highlight is mentioned - just a word count.

Gerry
 
Or any non-contiguous selection. Or a selection at all.

Gerry
 
Fumei,

You are correct there was no mention of selection or highlighting, and Speccy's code seems to do the trick.

My thinking was as follows:

Find, with the the "Highlight all items found in" option checked finds and highlights all occurances of a word. The highlight appears to be a multiSelect (although it may not be).

From there - with the find results still highlighted, the menu command Word Count lists, among other things, the number of words that are highlighted (selected).

This sequence provides the desired answer, along with other information.

Therefore thought I, it should be possible to replicate that sequence with VBA, and somehow get only the number of words, not the entire list of stuff that word count gives.

However my attempts at a solution along these lines have not been successful. I'm not very good at this stuff, and I'm trying to increase my knowledge. So, any insight into what may be wrong with my line of thought, or why selection.words.count with multiselect doesn't work would be appreciated.

It seems clear to me that Word has the capability to count the number of words that are highlighted (selected). Word count does return the number of words selected via a control-double-click mouse multiselect. So, if the Word Count command does not use selection.words.count, what does it use?
 
Do a non-contiguous multi-selection of words - say, four words. Tools > Word Count returns 4.

Using the SAME selection, run:
Code:
Msgbox Selection.Words.Count
and it returns 1.

This is because VBA does not recognize a non-contiguous Selection. In fact, you can not MAKE a non-contiguous selection with VBA. You can do it manually, holding the Ctrl key, but you can't do it with VBA.

In fact, say you have a selection like:

[COLOR=red yellow]This[/color] is a [COLOR=red yellow]sentence[/color] of [COLOR=red yellow]some[/color] text.

3 words selected: This, sentence, some

In VBA, the following code:
Code:
Msgbox "There are " & Selection.Words.Count & _
" words selected.  The text is " & _
Selection.Text
will return:

"There are 1 words selected. The text is some"

On a non-contiguous Selection Selection.Text returns only the LAST area selected.

The bottom line answer is Tools > Word count does in fact use Selection.Words.Count...but a different one...sort of. The "problem" lies in VBA. It does not recognize non-contiguous selection ranges. The Object Model ONLY has one set of parameters defined for Selection.Range....a .Start, and a .End. As in:

Selection.Range.Start
Selection.Range.End

So VBA simply can not see any other parts of the Selection, except the last one. Nor can it make any. VBA can not make non-contiguous Selections.

EXCEPT...this is not totally true. back to the example above. Three words selected. VBA returns a word count of 1. But say you add an instruction to DO something with that non-contiguous Selection? Say:

Code:
Selection.Font.Size = 20
Well, VBA will, in fact, action all non-contiguous parts of the Selection.

Here is another odd thing. Say you have a non-contiguous selection. You run the following:
Code:
Selection.MoveUp Unit:=wdParagraph, Count:=2, Extend:=wdMove
The selection is moved up two paragraphs.

Now...click the Undo button. Guess what happens? The previous Selection is re-selected....but ONLY the last area. It does NOT reselect non-contiguous areas.

Do the exact same thing, but manually. Have a non-contiguous selection, so something with it (say, make it bold). Click the selection up two paragraphs. Click Undo. The previous non-contiguous selection IS re-selected.

Non-contiguous selection are available through the User Interface, but not through VBA . Here is something even MORE odd. Same sort of example.

Say, three words non-contiguously selected. Run:
Code:
Selection.Font.Size = 16
Selection.MoveUp Unit:=wdParagraph, Count:=2, Extend:=wdMove
The non-contiguous selected words are font size 16, and the selection is moved up two paragraphs. Click the Undo button. Guess what?

ALL THREE non-contiguous areas are returned back to the previous state, but ONLY the last area is re-selected.

What can I say? The amazing world of Word!

As a final note, generally speaking it is preferable to use the Range object in VBA, over using the Selection object. And this is true. However, it is important to remember that while similar, Range and Selection ARE different objects.

Gerry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top