Counting References/paragraphs of a given style??

M

ML

We currently have a macro to loop through a document and cound "references"
which are marked with a specifc style so that we can find them. The issue
is that this code seems to be hanging Word and not sure why. Does anyone
have any ideas on what the issue is or a better way to handle this?

With ActiveDocument.Range.Find
.Style = "My Reference"
While .Execute
l = l + 1
If l > ActiveDocument.Range.Paragraphs.Count Then
GoTo endloop
End If
Wend
End With
endloop:
ActiveDocument.CustomDocumentProperties("RefCount") = l
 
J

Jay Freedman

The problem is that when you have two or more consecutive paragraphs with
the same My Reference style, the Find.Execute considers them to be only one
"found" instance. That means the variable l never exceeds the document's
paragraph count, so the loop never stops.

Since this approach doesn't work too well, try this instead:

Sub CountReferenceParas()
Dim aPara As Paragraph
Dim nRefs As Long

nRefs = 0
For Each aPara In ActiveDocument.Paragraphs
If aPara.Style = "My Reference" Then
nRefs = nRefs + 1
End If
Next

MsgBox "found " & nRefs & " references"
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
M

ML

Turned out that this line was the issue:
ActiveDocument.Range.Paragraphs.Count

Seems calling this in the loop took an extremely long amount of time and
perhaps has a memory leak. Called it once before the loop and set a
variable and it worked fine.
 
J

Jay Freedman

That must mean that none of your "My Reference" paragraphs are located
together, but are all separated by paragraphs with other styles. If
you ever run the macro on a document that does have consecutive
reference paragraphs, you'll see a real infinite loop, not just a slow
one.

I suggest you take Klaus's advice before that happens.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

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