Word, Paragraphs.Add does not return the paragraph that has just been added

Viewed 110

Consider this word document:

A word document with only one paragraph and some text inside it

Now, the following code should insert a new paragraph, and make it the selected one.

Sub Macro1()    
    Dim p As Paragraph       
    Set p = ActiveDocument.Content.Paragraphs.Add()
    p.Range.Select    
End Sub

Instead this is the result. A new paragraph has actually been added but then it selects the previous one.
That's a bit puzzling because no matter where you add the new paragraph, it should be that that is selected at the end and not the previous one.

enter image description here

1 Answers

A paragraph is a series of characters up to and including a paragraph sign.

In order to insert a paragraph after an existing paragraph, you need to position your insertion point after the existing paragraph sign.
This can be done for any paragraph except the last one. For the last paragraph, you can only go as far as immediately before its insertion point:

Dim r As Range

' Suppose there are 10 paragraphs
Set r = ActiveDocument.Paragraphs(3).Range
r.Collapse wdCollapseEnd
r.Select ' Places the caret after the 3rd paragraph sign

Set r = ActiveDocument.Paragraphs.Last.Range
r.Collapse wdCollapseEnd
r.Select ' Places the caret before the last paragraph sign

It is inconsistent and annoying, but that's what you get.

So when adding a paragraph to the very end, the insertion point is going to be before the existing paragraph sign, and thus the new paragraph sign is going to claim the old paragraph's body, becoming second-to-last.

So what you want is simply Set p = ActiveDocument.Content.Paragraphs.Last after the insertion.

Related