J West - revisit counting words in string?

E

Ed

The answer supplied by Jonathan West to me previous post is copied below:
Yes, you can, but first you need to define what you mean by a "word". For
instance is "apple-pie" one word or two?

If you want to take the simplest case of words being separated by spaces,
then the following line of code will do the trick

numWords = UBound(Split(stringWithWords, " ")) + 1

Unfortunately, when used with
Selection.MoveRight Unit:=wdWord, Count:=numWords
I get the wrong answer, because Word stops at every punctuation mark along
the way as well as spaces. So I didn't know what I was asking then - but
know a bit more now. Is there a way to count the words in a string as Word
would using Ctrl+Right Arrow?

Ed
 
J

Jonathan West

I did say that it depends on what you mean by a word :)

If you want to be sure that you are getting the same method as Word does,
then use Word's method. Insert the text into a document, select it, and get
the value of Selection.Words.Count.
 
K

Klaus Linke

Hi Ed,

Would have been easier to remain in the old thread ;-)
Unfortunately, when used with
Selection.MoveRight Unit:=wdWord, Count:=numWords
I get the wrong answer, because Word stops at every punctuation mark along
the way as well as spaces. So I didn't know what I was asking then - but
know a bit more now. Is there a way to count the words in a string as Word
would using Ctrl+Right Arrow?

If you (can) stay with the way Word counts words, you shouldn't run into
problems:

Dim numWords As Long
numWords = Selection.Words.Count
Selection.Collapse (wdCollapseStart)
Selection.MoveRight Unit:=wdWord, Count:=numWords

That would be a rather clumsy way to move the IP to the end of a
selection...

If you could post what you are trying to do, we might come up with more
specific tips.

Regards,
Klaus
 
E

Ed

Sorry, I guess I should be more clear. I have an InputBox; the user's input
is set to a String variable. I then find that string in the document and
select it. I then have to extend the selection by a number of "words" (as
counted using Ctrl+Right Arrow), which is predetermined by another InputBox.
I figured the easiest way was to Find and Select the String, Collapse to the
start, then select the number of "words" in the string plus the other
amount. Am I doing this the hard way?

Ed
 
S

sestyd

JWest & Ed,

I though this was pretty interesting, and since I'm trying
to figure out all the methods (after actually finding the
documentation on the darned things), I wrote this sub
which prints out the count from the count method.

When I counted this paragraph by hand I got 58. The count
method counts 59. when I actually print the words out,
word 59 seems to be a carriage return or maybe it's empty,
not sure yet. Word behaves the same way whether I add this
text to a paragraph, section, or just to the document
content. Does anyone know why that is?

Anyway, try this sub (unwrap the lines). It probably will
work consistantly if you subtract 1 from the count.

Vera

Sub countWords()

Dim strText As String
Dim i As Integer

strText = "I get the wrong answer, because Word stops at
every punctuation mark along the way as well as spaces.
So I didn't know what I was asking then - but know a bit
more now. Is there a way to count the words in a string
as Word would using Ctrl+Right Arrow?"

With ActiveDocument
.Paragraphs.Add 'add the introductory paragraph
.Paragraphs(1).Range.Text = strText 'add text to it

intWords = .Paragraphs(1).Range.Words.Count

Debug.Print "Word count: " & intWords
For i = 1 To intWords
Debug.Print "word " & i & ": " & .Paragraphs
(1).Range.Words.Item(i).Text
Next

End With

End Sub
 
K

Klaus Linke

Ed said:
I have an InputBox; the user's input is set to a String variable.
I then find that string in the document and select it.
I then have to extend the selection by a number of "words" (as
counted using Ctrl+Right Arrow), which is predetermined by
another InputBox.
I figured the easiest way was to Find and Select the String, Collapse to the
start, then select the number of "words" in the string plus the other
amount. Am I doing this the hard way?

You wouldn't need to collapse the selection. Just move the end by the number
of words specified in your second InputBox:

Selection.MoveEnd Unit:=wdWord, Count:=numWords

But Ctrl+Right Arrow also counts punctuation marks as words.
If a user enters a number in the input box, he might not be aware of that.

If you *don't* want to count punctuation marks/paragraph marks... as words,
you would need to write a loop:
-- Do
-- move the end of the selection one "word",
-- get the last "word" (Selection.Words.Last.Text),
-- if the text of that "word" only contains white space and punctuation
marks, don't increment the counter,
-- else, increment the counter by one,
-- Loop until the counter is equal to numWords.

Regards,
Klaus
 
E

Ed

Vera, that was great! I was hoping there was a method that would let me do
this "inside" VBA, without having to print the string into the document, but
I can sneak it in, get what I need, and delete it back out before anyone
notices. 8>)

(BTW, I have a book which (so it says) lists out every object, property, and
method in Word VBA. It's "Word 2000 Developer's Handbook" (ISBN
0-7821-2329-5). Halfpricecomputerbooks.com has one for 24.99. It's worked
okay for me so far - as long as I know enough to know what to look up!)

Ed
 
G

Guest

Ed,

Actually, you should just be able to pass your string to
the sub in a string variable.

sub countWords(ByVal strText as string)
or better yet

function countWords(ByVal strText as string) as integer
code, code, code



end function


so I think you can probably pass the selection in, not
sure about that

if you use the function then it will return the count to
you
 
E

Ed

Thanks, Klaus. I think I've got enough to play with for now - almost more
than I can juggle without dropping! I'll work this through and yell for
help if need be. I appreciate all your input.

Ed
 
V

vera

Ed,

Whoops! Hit the wrong button!
I'll work out the function if you get stuck. Thanks for
the book tip!

Vera
 
V

vera

Ed,

Oh, heck, I just had to try something else. Try this by
creating a new word doc, putting some text on it,
selecting the text, then run the sub testWordCount in your
immediate window. And don't forget to unwrap the lines.

Vera


Function countWords() As Integer

Dim i As Integer

intWords = selection.Words.Count - 1

Debug.Print "Word count: " & intWords
For i = 1 To intWords
Debug.Print "word " & i & ": " &
selection.Words.Item(i).Text
Next

countWords = intWords

End Function

Sub testCountWords()

Dim intWordCount As Integer
intWordCount = countWords()
Debug.Print "Here is the word count: " & intWordCount

End Sub
 
J

Jay Freedman

Hi, Ed,

As a completely different alternative, have a look at the
Selection.Extend method.
 
B

Bruce Brown

Hi, gang

This is a homely old sleighdog of a macro but I'd be curious to see
how else an accurate word count could be arrived at for the following
sentence:

"One + two - three = four," five, 6, seven; "eight nine ten!!!"
Eleven twelve>>thirteen<< fourteen? '"` ~15||| . . .
'sixteen'\.^seventeen``= (eighteen@nineteen%):::::


$twenty???

Code:

(Place cursor before first word.)

Dim R As Range, WordCnt As Integer
Set R = Selection.Range
Do
R.MoveEndWhile vbCr & vbTab & Chr(160) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
R.MoveEnd wdWord
R.MoveEndWhile vbCr & vbTab & Chr(160) & "
..,;:'()[]!@#$%^&*-_+={}~`\/?<>|"""""
WordCnt = WordCnt + 1
R.Select
MsgBox WordCnt, , "WordCnt"
Loop Until WordCnt = 20
Selection.Collapse

P.S. Won't work with "smart" quotes or em dashes.

- Bruce
 
B

Bruce Brown

Here are three more word-counting sleighdogs, slightly more refined
but still slobbering. The first one's a little more fun than the
others. This time they skip "smart" quotes too.

The third one, count-all-words-in-doc, took about 5 seconds to find
over 26,000 words and about 10 seconds to find over 45,000 words.

Add characters to skip, as needed, within the MoveEndWhile statement.


'========================================================================
Sub CountUserSpecifiedNumberOfWords()
'COUNT USER-SPECIFIED NUMBER OF WORDS, STARTING AT INSERTION POINT
'SKIP ANYTHING OTHER THAN WORDS OR NUMBERS
If Selection.Type <> wdSelectionIP Then
MsgBox "Quitting.", , "Text Can't Be Selected"
Exit Sub
End If
Dim R As Range, X As Range, WordCnt As Long, UserNumber As Long
UserNumber = InputBox("Number of words:", "Number of Words to Count",
10)
Set R = Selection.Range
Do
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
Set X = R.Duplicate
X.Start = X.End
X.MoveEnd wdWord
X.Select
WordCnt = WordCnt + 1
MsgBox X.Text, , WordCnt
R.MoveEnd wdWord
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
Loop Until WordCnt = UserNumber
Selection.Collapse
End Sub


'========================================================================
Sub CountWordsInSelectedText()
'COUNT WORDS IN BLOCK OF SELECTED TEXT
'SKIP ANYTHING OTHER THAN WORDS OR NUMBERS
If Selection.Type = wdSelectionIP Then
MsgBox "Quitting.", , "Nothing Selected"
Exit Sub
End If
Dim R As Range, WordCnt As Long
Set R = Selection.Range.Duplicate
R.End = R.Start
Do While R.End < Selection.Range.End
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
R.MoveEnd wdWord
WordCnt = WordCnt + 1
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
Loop
MsgBox WordCnt
End Sub


'========================================================================
Sub CountAllWordsInWholeDoc()
'COUNT ALL WORDS IN MAIN STORY RANGE OF DOCUMENT
'SKIP ANYTHING OTHER THAN WORDS OR NUMBERS
Dim R As Range, X As Range, WordCnt As Long
Set X = ActiveDocument.Range.Duplicate
X.End = X.End - 1
Set R = Selection.Range
Do While R.End < X.End
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
R.MoveEnd wdWord
WordCnt = WordCnt + 1
R.MoveEndWhile vbCr & vbTab & Chr(160) & Chr(147) & Chr(148) & "
..,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
Loop
MsgBox WordCnt, , "WordCnt for Whole Doc"
End Sub


Hi, gang

This is a homely old sleighdog of a macro but I'd be curious to see
how else an accurate word count could be arrived at for the following
sentence:

"One + two - three = four," five, 6, seven; "eight nine ten!!!"
Eleven twelve>>thirteen<< fourteen? '"` ~15||| . . .
'sixteen'\.^seventeen``= (eighteen@nineteen%):::::


$twenty???

Code:

(Place cursor before first word.)

Dim R As Range, WordCnt As Integer
Set R = Selection.Range
Do
R.MoveEndWhile vbCr & vbTab & Chr(160) & "
.,;:'()[]!@#$%^&*-_+-={}~`\/?<>|"""""
R.MoveEnd wdWord
R.MoveEndWhile vbCr & vbTab & Chr(160) & "
.,;:'()[]!@#$%^&*-_+={}~`\/?<>|"""""
WordCnt = WordCnt + 1
R.Select
MsgBox WordCnt, , "WordCnt"
Loop Until WordCnt = 20
Selection.Collapse

P.S. Won't work with "smart" quotes or em dashes.

- Bruce

Jay Freedman said:
Hi, Ed,

As a completely different alternative, have a look at the
Selection.Extend method.
 

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