none
Insert multiple paragraphs inside an existing document RRS feed

  • Question

  • Hi, 

    I need to insert multiple paragraphs with different styles, and that sound not so easy. The paragraphs should be created at a specific place, located by a bookmark.

    The code below create paragraphs like :

    Line 2

    Line 1

    ...instead of 

    Line 1

    Line 2.

    I don't understand why... :-(

    Thanks.

    Xavier.

    Public Sub InsertParagraph()
    
    Dim bm As Bookmark
    Set bm = ActiveDocument.Content.Bookmarks("MyBookMark")
    bm.Select
    
    Dim p As Paragraph
    Set p = ActiveDocument.Content.Paragraphs.Add(bm.Range)
    p.Range.InsertAfter ("Line 1")
    
    Dim r As Range
    Set r = p.Range
    
    Set p = ActiveDocument.Content.Paragraphs.Add(r)
    p.Range.InsertAfter ("Line 2")
    
    End Sub
    


    Tuesday, August 19, 2014 1:33 PM

Answers

  • Hi Xavier

    If you walk through your code (F8 in the VBA Editor) you'll see that Paragraphs.Add is inserting the new paragraph BEFORE the target Range, not after as you might expect.

    Try something along these lines:

    Dim r As word.Range
    Set r = ActiveDocument.Bookmarks("MyBookmarK").Range
    r.Text = vbCr & "Line1"
    r.Collapse wdCollapseEnd
    r.Text = vbCr & "Line 2"
    

    Think of the Collapse method as when you'd press the right arrow key (or left arrow) to change a selection (the Range content) to a blinking cursor. So you're moving the "focus" in the range to the end of the range. vbCr is the equivalent of pressing Enter - inserting a new paragraph.


    Cindy Meister, VSTO/Word MVP, my blog

    Tuesday, August 19, 2014 5:02 PM
    Moderator