Add paragraph to Paragraphs collection?

K

Klaus Linke

Say I've got

Dim myParas As Paragraphs
Dim myPara As Paragraph

' myParas = first and second paragraph in doc
Set myParas = ActiveDocument.Range(0,
ActiveDocument.Paragraphs(2).Range.End).Paragraphs

' myPara = fifth paragraph in doc
Set myPara = ActiveDocument.Paragraphs(5)

.... then there is no way to add myPara to myParas, so that myParas contains
the first, second, and fifth paragraph?

One could use an array to store the paragraphs (either an array of the
paragraphs themselves, or of their index number), but putting them in the
collection would seem a nicer way, if it were possible.

The collection probably simply does not work like that ... but I thought it
might be worth checking if I've missed something.

Regards,
Klaus
 
L

Lene Fredborg

You could use the Collection object and create a New Collection consisting of
the desired paragraphs. Actually, I only remember having used this method
once. I think I normally forget about the Collection object but reading your
question reminded me of this possibility. The code below creates a collection
consisting of paragraphs 1, 2 and 5 of the active document:

Sub TestCollectionOfParagraphs()

Dim oColl As New Collection 'used for creating a new collection of
specific paragraphs
Dim oElement As Variant
Dim oPara As Paragraph

Dim n As Long

'Add the desired paragraphs to the oColl
With oColl
.Add ActiveDocument.Paragraphs(1)
.Add ActiveDocument.Paragraphs(2)
.Add ActiveDocument.Paragraphs(5)
End With

'Now oColl includes paragraphs 1, 2 and 5 of the active document
For n = 1 To oColl.Count
MsgBox oColl(n)
Next n

End Sub

--
Regards
Lene Fredborg - Microsoft MVP (Word)
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word
 
K

Klaus Linke

Hi Lene,

Yes, thank you! That is what I ended up doing. Though I needed some
additional code to make sure I don't put the same paragraph in the
Collection more than one time.

I guess the built-in "collections" like the Paragraphs [or Words, Tables,
Bookmarks...] collection are very slim, and little more than a shortcut for
"all the paragraphs [words, tables, bookmarks...] in a certain Range".

Regards,
Klaus
 

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