Search code examples
excelvbams-wordword-contentcontrol

Is it possible to add Repeating Section Content Control section with VBA?


I have created Word template with Repeating Section Rontent Control (RSCC) containing other Content Controls. Also I have excel workbook with information which should go to mentioned Word template. The thing I am trying to do is to create macro which would fill Word template with information from selected rows in Excel workbook (each row to new RSCC section).

I have quite good idea how to do that, except one thing- I cannot figure out how to write macro which would add another section to Repeating Section Content Control.

I am adding illustrations of what I am trying to do:

example

Problem is, that I cannot find code to do the same thing with VBA. I have tried recording process, but recorded macro is empty (?!).

Looking for answer I have found this thread in StackOverflow, it ask similar question to mine, but it was more or less unanswered to my understanding. Comment in this thread forwarded to old thread in Microsoft forum, but I did not find solution to this problem (or at least I did not understand clearly how should I approach it).

Since one thread is almost 5 years old, another 2 years old. My question is it even possible to add another section to RSCC with VBA? Maybe somebody found a way to do this in the past year or so?


Solution

  • The Word object model has a collection and object for a repeating section content control: RepeatingSectionItems and RepeatingSectionItem. The latter has two insert methods, to insert before or after the RepeatingSectionItem.

    Here's a sample that shows how to reference a repeating section content control in a document, get the first or last item and insert a new one after it.

    Sub AddRepeatingSection()
        Dim cc As Word.ContentControl
        Dim repCC As Word.RepeatingSectionItem
    
        Set cc = ActiveDocument.SelectContentControlsByTitle("RepCC").Item(1)
        Set repCC = cc.RepeatingSectionItems.Item(1)
        'Or to get the last one:
        'Set repCC = cc.RepeatingSectionItems.Item(cc.RepeatingSectionItems.Count)
        repCC.InsertItemAfter        
    End Sub