vbams-wordword-style

VBA in Word: Programmatically add content control with a style


When programatically adding a rich text content control to a Word .docm using VBA, is there a way to set a style for the contents?

As a comparison, if I create a content control manually using the Word Developer toolbar, I can select "Use a style to format contents" in the properties dialog for the content control. The result I want is the same as if I did it that way, except I need to do it in code.

Here's the code I have that adds the content control, it's triggered by a command button click that does a few other things as well:

Private Sub selConcept_Click()

    ActiveDocument.InlineShapes(1).Delete
    ActiveDocument.InlineShapes(3).Delete
    ActiveDocument.InlineShapes(3).Delete

    Dim oCC As ContentControl
    Set oCC = ActiveDocument.ContentControls.Add(wdContentControlRichText, _
              Selection.Range)
    oCC.SetPlaceholderText , , "My placeholder text is here."
    oCC.Title = "Concept"
End Sub

Solution

  • If you already created the style, you can just assign it like this:

    oCC.DefaultTextStyle = "style_name"
    

    Now, if not, you'll have to add your style first. Something like:

    ActiveDocument.Styles.Add Name:="MyStyle1", Type:=wdStyleTypeCharacter
    With ActiveDocument.Styles("MyStyle1").Font
        .Name = "Arial"
        .Size = 12
        .Bold = True
        .Color = RGB(255, 0, 0) 'you can use RGB here
    End With
    
    oCC.DefaultTextStyle = "MyStyle1"