Can a character style be applied programmatically

2019-08-22 02:04发布

问题:

I am grabbing some data from an Excel sheet and populating it into a Word template. I'm hoping that I can assign some of the Document's character styles to sub strings that will be added to the Document as the string is built up rather than having add the string to the Document and then select each string individually to apply the appropriate style.

Right now, I'm concatenating a few strings and adding them to a text box in the document like this:

ActiveDocument.Shapes("Text Box 7").TextFrame.TextRange.Text = str1 & " " & str2 & ", " & str3

This runs in a loop and prints several of these lines to the Document. I would, however, like to assign/apply a different character style to str1, str2 and str3 on each line as it's being written to the Document. Something like:

ActiveDocument.Shapes("Text Box 7").TextFrame.TextRange.Text =
    str1.applyStyle("charStyle1") & 
    " " & 
    str2.applyStyle("charStyle2") & 
    ", " &
    str3.applyStyle("charStyle3")

I realize there is no String.applyStyle() method, but is there anything that can be done that comes close to this functionality or does the string have to be written to the Document first and then loaded into a Range object and THEN have its Style property set?

回答1:

With ActiveDocument.Shapes("Text Box 7").TextFrame.TextRange
  .Style = "Style1"
  .Text = str1 & " "
  .Collapse wdCollapseEnd
  .Style = "Style2"
  .Text = str2 & ", "
  .Collapse wdCollapseEnd
  .Style = "Style3"
  .Text = str3
End With