VBA in Word: Programmatically add content control with a style

半腔热情 提交于 2021-01-27 16:01:24

问题


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

回答1:


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"


来源:https://stackoverflow.com/questions/29859677/vba-in-word-programmatically-add-content-control-with-a-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!