none
Using Word VBA to add two content controls with a carriage return in between RRS feed

  • Question

  • I'm very comfortable with VBA in Excel, but I'm having trouble with the Word object model. I'm trying to use VBA to add a content control, go down one line, and add another content control. I can get ContentControls.Add to work, and I can get Selection.TypeParagraph to work, but I don't see how to get the carriage return between the two controls.

    Thanks,

    Dom

    Friday, October 17, 2014 6:05 PM

Answers

  • Two approaches:

    Sub Demo1()
    Selection.Text = vbCr & vbCr
    With ActiveDocument.ContentControls
      .Add wdContentControlRichText, Selection.Paragraphs.First.Range
      .Add wdContentControlRichText, Selection.Paragraphs.Last.Range
    End With
    End Sub

    Sub Demo2()
    Dim Rng As Range
    Set Rng = Selection.Range
    With ActiveDocument.ContentControls
      .Add wdContentControlRichText, Rng
      With Rng
        .InsertBefore vbCr
        .Collapse wdCollapseStart
      End With
      .Add wdContentControlRichText, Rng
    End With
    End Sub

    The first one assumes you're working with selections (generally not good practice) and inserts the content controls in the normal order. It can, of course, be modified to work with Range objects. The second works with range objects but inserts the controls in the reverse order.


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Friday, October 17, 2014 8:45 PM