Search code examples
vbams-wordword-contentcontrol

How to add Content Control before bookmark?


I want macro to add Content Control before bookmark. I am having trouble figuring out syntax for "before" part since .Range.InsertBefore works only with string.

Please give me some direction how to change my code to make new Content Conrols to be inserted before bookmark.

My current code for inserting Content Control:

Sub Test()

    Dim objCC As ContentControl
          'it inserts Content control after bookmark, not before, how to change this part?
    Set objCC = ActiveDocument.ContentControls.Add(0, ActiveDocument.Bookmarks("VP_pav").Range)
    objCC.Title = "Test"

    End Sub

Solution

  • Bookmarks aren't substantial "objects" in the text flow, the way a character is, so it's not possible to insert anything immediately before a bookmark. The insertion position would have to be moved at least one character back from the bookmark.

    The only way to have the bookmark directly after the content control is to delete and recreate the bookmark. Here's an example. Note the use of Range objects to keep track of where the content control is and where the bookmark is. This example is for an "I-beam" bookmark: a bookmark that is a single position, not a range of characters.

    Sub InsertCCbeforeBookmark()
        Dim bkm As Bookmark, sBookmarkName As String
        Dim rngBookmark As Word.Range, rngCC As Word.Range
        Dim objCC As ContentControl
    
        sBookmarkName = "VP_pav"
        Set bkm = ActiveDocument.Bookmarks(sBookmarkName)
        Set rngBookmark = bkm.Range
        Set rngCC = rngBookmark.Duplicate
        rngCC.Collapse wdCollapseStart
        Set objCC = ActiveDocument.Contentcontrols.Add(0, rngCC)
        rngBookmark.Start = objCC.Range.End
        rngBookmark.MoveStart wdCharacter, 1
        bkm.Delete
        ActiveDocument.Bookmarks.Add sBookmarkName, rngBookmark
        objCC.title = "Test"
    
    End Sub