Inserting a field to count number of words in previous paragraph

A

andy.cotgreave

Hi,
I need to create a field which counts the number of words in the
preceeding paragraph.

And I'm actually completely stuck - VBA to navigate around a document
not something I have ever worked with. I'm pretty comfortable with
fields, but it's the paragraph selection that loses me.

Thanks in advance

Andy
 
D

Doug Robbins - Word MVP

It can't be done with fields alone. You could use a DOCVARIABLE field and
then use VBA to load the number of words into the variable

To get the number of words in the ith paragraph of the document, you would
use

ActiveDocument.Paragraphs(i).Range.Words.Count

If you had a field { DOCVARIABLE varparai }

you could use

With ActiveDocument
.Variables("varparai").Value = .Paragrapsh(i).Range.Words.Count
.Range.Fields.Update
End With

to get the number of words to be displayed in that field.

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
A

andy.cotgreave

It can't be done with fields alone. You could use a DOCVARIABLE field and
then use VBA to load the number of words into the variable

To get the number of words in the ith paragraph of the document, you would
use

Hi Doug,
Thanks for the suggestion - sounds good.

One question remains, though! Each field needs to refer to the
paragraph above it - how do I work out the number of the paragraph in
the document relative to the position of the field?

Thanks

Andy
 
D

Doug Robbins - Word MVP

The following macro will add a field that displays [## words] at the end of
each paragraph in a document:

Dim i As Long
Dim varname As String
Dim frange As Range
With ActiveDocument
For i = 1 To .Paragraphs.Count
varname = "Para" & i
.Variables(varname).Value = " [" & .Paragraphs(i).Range.Words.Count
& " words]"
Set frange = .Paragraphs(i).Range
frange.End = frange.End - 1
frange.Collapse wdCollapseEnd
.Fields.Add Range:=frange, Type:=wdFieldDocVariable, Text:=varname
Next i
.Fields.Update
End With


--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
A

andy.cotgreave

The following macro will add a field that displays [## words] at the end of
each paragraph in a document: ...snip...

Excellent!
Thanks for your help, that's just what I was after.
 

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