VBA to Word: Add Content Control Programmatically in Style

While programmatically adding a text content control to Word.docm using VBA, is there a way to set the style for the content?

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

Here is the code I have that adds a content control, it is triggered by a command button click, which 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

      

+3


source to share


1 answer


If you've already created a style, you can simply assign it like this:

oCC.DefaultTextStyle = "style_name"

      



Now if not, first you need to add your style. 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"

      

+1


source







All Articles