Search code examples
vbams-wordword-2007

MS Word VBA script to add Bookmarks to Existing Content Controls


I have over 150 Content Control (CC) boxes within a document and was wondering if someone would be able to help me with VBA script to add bookmarks to them programmatically. The names for the new bookmarks would have to match the Title or Tags I've inserted for the CCs. For example, if I have a CC in the document with the title 'TestResults' I'd like the bookmark called 'TestResults' to be inserted on that CC. I'm an absolute beginner to VB!

So I guess I want the code to do the following:

  1. Find all the CCs in the document and their titles
  2. Insert bookmarks matching the CC title.

Solution

  • This should work for you:

    Sub AddBookmarksAtCC()
        Dim ccobjA As ContentControl, i As Integer
        For i = 1 To ActiveDocument.ContentControls.Count
            Set ccobjA = ActiveDocument.ContentControls.Item(i)
            Debug.Print ccobjA.Title
            ActiveDocument.Bookmarks.Add ccobjA.Title, ActiveDocument.ContentControls.Item(i).Range
        Next i
    End Sub
    

    This procedure will count all Content Controls on the document, and loop though them all, adding a bookmark at each one. As it is, the bookmark will be named the title of the content control. If you want to make it the Tag, replace ccobjA.Title with ccobjA.Tag. Let me know if you are still having trouble.