VBA Append and Remove building blocks to the start of a bookmark

How can I append a quick part/building block to the start of a bookmark in VBA and keep a reference to it in a list for removal or hiding later?
ag1iffitAsked:
Who is Participating?
 
GrahamSkanRetiredCommented:
With that (and your apologetic message) in mind, yes, you could enclose new insertions into the bookmark. If you only concerned with one bookmark, you could do it like this:

   
Dim doc As Document
    Dim rng As Range
    Dim rng1 As Range
    Dim MyTemplate As Template
    Dim strContainedBlocks() As String
    Dim i As Integer
    Dim j As Integer
    Dim strMsg As String
    '...
    'template and doc objects set here
    '...
    With doc
        Set rng = doc.Bookmarks("MyBookmark").Range
        Set rng1 = rng.Duplicate
        rng.Collapse wdCollapseEnd
        MyTemplate.BuildingBlockEntries("MyBlock").Insert rng, True
        rng.Start = rng1.Start
        doc.Bookmarks.Add "MyBookmark", rng
        ReDim Preserve strContainedBlocks(i)
        strContainedBlocks(i) = "MyBlock"
        i = i + 1
        
        Set rng = doc.Bookmarks("MyBookmark").Range
        Set rng1 = rng.Duplicate
        rng.Collapse wdCollapseEnd
        MyTemplate.BuildingBlockEntries("MyNewBlock").Insert rng, True
        rng.Start = rng1.Start
        doc.Bookmarks.Add "MyBookmark", rng
        ReDim Preserve strContainedBlocks(i)
        strContainedBlocks(i) = "MyNewBlock"
        i = i + 1
   End With
   strMsg = "Mybookmark contains "
    For j = 0 To i - 1
        strMsg = strMsg & strContainedBlocks(j) & ", "
    Next j
    MsgBox strMsg

Open in new window

0
 
GrahamSkanRetiredCommented:
I suggest that you insert the text into the bookmark, so that the bookmark can later be used to find the inserted text. You can use a collection to keep a list of which building block is in each bookmark
    Dim doc As Document
    Dim rng As Range
    Dim MyTemplate As Template
    Dim coll As New Collection
    
    '...
    'template and doc objects set here
    '...

    With doc
        Set rng = doc.Bookmarks("MyBookmark").Range
        MyTemplate.BuildingBlockEntries("MyBlock").Insert rng, True
        doc.Bookmarks.Add "MyBookmark", rng 're-add bookmark to ensure that it defines the new text
        coll.Add "MyBlock", "MyBookmark"
    End With
    
    MsgBox "Mybookmark contains " & coll("MyBookmark")

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.