使用 VBA 在 Word 中插入粗体文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3966984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert bold text into Word using VBA
提问by skerit
I wrote a little script that exports certain Excel cell values into Word. However, certain inserts need to be bold. And there doesn't seem to be an easy way to do this.
我写了一个小脚本,将某些 Excel 单元格值导出到 Word 中。但是,某些插入内容需要加粗。似乎没有一种简单的方法可以做到这一点。
This code loops through the records and adds them to the Word document
此代码遍历记录并将它们添加到 Word 文档中
Do While intRow < intTotalRows + 1
strTemp = " ;b;" & Range("G" & intRow).FormulaR1C1 & " " & Range("I" & intRow).FormulaR1C1 & ";e; "
If strTemp <> strCur Then
strCur = strTemp
.Content.Font.Bold = True
.Content.InsertAfter strCur
End If
.Content.Font.Bold = False
.Content.InsertAfter Range("A" & intRow).FormulaR1C1 & " - " & Range("C" & intRow).FormulaR1C1 & " " & Range("E" & intRow).FormulaR1C1 & " * "
intRow = intRow + 1
Loop
Turning on bold before inserting text and turning it off again afterwards seems like the most logical solution, so it does not work.
在插入文本之前打开粗体并在之后再次关闭它似乎是最合乎逻辑的解决方案,因此它不起作用。
I then tried to find and replace the text, but that also did not work:
然后我尝试查找并替换文本,但这也不起作用:
.Content.Find.ClearFormatting
With .Content.Find
.Text = ";b;" 'Look for
.Replacement.Text = ";bbb;" 'Replace with
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
.Content.Find.Execute Replace:=wdReplaceAll
采纳答案by Dirk Vollmar
Replace .InsertAfter
with .TypeText
. Inserting works like pasting whereas TypeText
works like if you would actually type the text on the keyboard.
替换.InsertAfter
为.TypeText
。插入就像粘贴TypeText
一样工作,而就像您实际在键盘上键入文本一样。