Search code examples
vbams-wordword-2016

How to prevent Repeat Content Control nesting (word 2016)


I'm having an issue with a form I'm building in word 2016 and can't really find anything from Microsoft except the general documentation for ContentControls and BuildingBlocks.

Here is an example of a simple Word form I'm trying to create with add and remove command buttons and a repeating content control named InspectorName and tagged InspectorName:

enter image description here

I inserted this content control as a BuildingBlock using the following vba code whilst highlighting the content control before the paragraph mark

Public Sub getTemplateName()
 Dim objTemp As Template
 Dim myrange As Range
 Dim myblock As BuildingBlock
 Set objTemp = ActiveDocument.AttachedTemplate
 Set myrange = Selection.Range
 Set myblock = objTemp.BuildingBlockEntries.Add("InspectorName", _
 wdTypeCustom1, "InspectorName", myrange)
End Sub

I am now trying to build a procedure where if there exists a content control (i.e. the count is not 0) then the building block built with the above procedure will be inserted using the collapsed range of the last content control inserted. Here is the code I have below.

Public Sub insertBuildingBlock()
 Dim objBB As BuildingBlock
 Dim myrange As Range
 Dim objTemp As Template
 Dim mycount As Integer
 Set objTemp = ActiveDocument.AttachedTemplate
 Set objBB = objTemp.BuildingBlockTypes(wdTypeCustom1) _
.Categories("InspectorName").BuildingBlocks("InspectorName")
 mycount = ActiveDocument.SelectContentControlsByTag("InspectorName").Count
 If mycount <> 0 Then
  Set myrange = ActiveDocument.SelectContentControlsByTag("InspectorName"). _
  Item(mycount).Range
  myrange.Collapse wdCollapseEnd
  objBB.Insert myrange
 End If
End Sub

After this code runs this occurs - the two content controls are nested.

enter image description here

I have tried almost everything I know, so any input would greatly be appreciated !


Solution

  • When you collapse a content control's Range the "focus" of the range is still within the content control. Add this line:

      myrange.MoveStart wdCharacter, 1
    

    Full code:

    Public Sub insertBuildingBlock()
     Dim objBB As BuildingBlock
     Dim myrange As Range
     Dim objTemp As Template
     Dim mycount As Integer
     Set objTemp = ActiveDocument.AttachedTemplate
     Set objBB = objTemp.BuildingBlockTypes(wdTypeCustom1) _
    .Categories("InspectorName").BuildingBlocks("InspectorName")
     mycount = ActiveDocument.SelectContentControlsByTag("InspectorName").Count
     If mycount <> 0 Then
      Set myrange = ActiveDocument.SelectContentControlsByTag("InspectorName"). _
      Item(mycount).Range
      myrange.Collapse wdCollapseEnd
      myrange.MoveStart wdCharacter, 1  '<-----
      objBB.Insert myrange
     End If
    End Sub