Help Understanding Range Objects

G

Greg

I recently worked with some code like this

Dim aWord As Range

For each aWord in ActiveDocument.Words

Do something

Next aWord

Now I am trying to work with paragraphs. I started with code like this:

Dim aParagraph As Range
For each aParagraph in ActiveDocument.Paragraphs

Do something

Next aParagraph

With this code I am getting a RTE '13' Type mismatch.

What is causing this error? Thanks.
 
E

Ed

The paragraph is an object, and is part of the Paragraphs collection. Each
paragraph has a range that can be accessed, and objects within that range.
To work with a specific paragraph, try

Dim objPar As Paragraph

For Each objPar In ActiveDocument.Paragraphs
MsgBox objPar.Range.Words(1)
Next objPar

HTH
Ed
 
J

Jonathan West

Hi Greg,

The Characters collection is a collection of objects in the document, each
of which is a Range object one character long

Similarly, the Words collection is a collection of Range objects each one
word long.

The Paragraphs collection is different, it is a collection of Paragrarph
objects. Each Paragraph object has a Range property which defines the text
of the paragraph. The reason that the paragaraphs collection is different is
that Paragraph objects have properties associated with the paragraph
formatting. You need to code like this

Dim aParagraph As Paragraph
For each aParagraph in ActiveDocument.Paragraphs

With aParagraph.Range
Do something
End With

Next aParagraph
 
G

Greg

Ed,

Got it. Thanks for the nudge.

Ed said:
The paragraph is an object, and is part of the Paragraphs collection. Each
paragraph has a range that can be accessed, and objects within that range.
To work with a specific paragraph, try

Dim objPar As Paragraph

For Each objPar In ActiveDocument.Paragraphs
MsgBox objPar.Range.Words(1)
Next objPar

HTH
Ed
 
G

Greg

Jonathan,

Thanks for the tips. Was looking for a means to count bolded paragraphs in
a document. I saw Ed's post earlier and put together the following:

Sub Test3()
Dim j As Long, objPar As Paragraph
j = 0
For Each objPar In ActiveDocument.Paragraphs
If objPar.Range.Font.Bold = True Then j = j + 1
Next objPar
MsgBox "There are " & j & " bolded entries in this document"
End Sub
 

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