Word Count

G

Guest

Hi

I've tried to find a solution to my problem by looking through the messages
boards, but so far no luck.

I have a document with 3 sections. I would like to do a word count of
section 2, and put the result (perhaps as a field, or vba to bookmark?) into
section 1. I would also like this word count to update on; printing, saving,
or closing.

I've thought of containing section 2 within a bookmark, if that makes it any
easier to do the word count.

Does anyone have a solution???

Cheers, Ty
 
S

Shauna Kelly

Hi Ty

The field used to count the number of words is the NUMWORDS field. But there
are no switches to use with this field to restrict it to part of a document.

You could automate this with VBA. To do that, you would need to do three
things.

1. Put a bookmark in Section 1 called, say, WordCount.

2. Write some code that is something like the following (note that this has
no error checking, which you would need to add):

Sub InsertWordCount()

Dim oRange As Word.Range
Dim sBookmarkName As String

sBookmarkName = "WordCount"
With ActiveDocument
Set oRange = .Bookmarks(sBookmarkName).Range
oRange.Delete
oRange.InsertAfter Text:=Format(.Sections(2).Range.Words.Count, "0")
.Bookmarks.Add Name:=sBookmarkName, Range:=oRange
End With

End Sub


3. Intercept the print, save, save as and file close events to run your
code. How to intercept events is described here:
Intercepting events like Save and Print
http://www.word.mvps.org/FAQs/MacrosVBA/InterceptSavePrint.htm

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 
G

Guest

Hi Shauna

That is absolutely awesome! Thank you so much. I'm not sure about error
checking (I don't know enought about VBA), but the code you gave works
perfectly when called from AutoOpen and FileSave (with the save command as
well).

Many thanks, Ty.
 
G

Guest

I have tweaked the code as follows:

Sub InsertWordCount()
Dim oRange As Word.Range
Dim sBookmarkName As String

sBookmarkName = "WordCount"
With ActiveDocument
Set oRange = .Bookmarks(sBookmarkName).Range
oRange.Delete
oRange.InsertAfter
Text:=Format(.Sections(2).Range.ComputeStatistics(wdStatisticWords), "0")
.Bookmarks.Add Name:=sBookmarkName, Range:=oRange
End With
End Sub


With the other code it included each item of punctuation as one word. For
example:

My first, paragraph!
returned 6 word with the previous code (as Word counted punctuation
[comma and exclamation point in this case] and paragraph marks as one word).

I hope this tweak is of benefit to other users.

Cheers, Ty
 

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