Can a character style be applied programmatically to a string before it is written to the Word document with VBA?

青春壹個敷衍的年華 提交于 2020-01-16 16:57:23

问题


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


来源:https://stackoverflow.com/questions/50186012/can-a-character-style-be-applied-programmatically-to-a-string-before-it-is-writt

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