在word中可以通过“开始”选项卡下的“字体”工作组中的“文本突出显示颜色”命令给文档中的文本添加高亮显示的背景填充色,如下图所示:

在word vba中,可以使用Range对象的HighlightColorIndex属性获取或者设置高亮的背景填充色。
以下vba代码举例演示了如何为word文档中的所有特定文本字符(“测试”)添加高亮背景填充色:
Sub QQ1722187970()
Const wdYellow = 7
Const wdGreen = 11
Const wdBlue = 2
Const wdAuto = 0
Const wdNoHighlight = 0
Dim oRegExp As Object
Set oRegExp = CreateObject("vbscript.regexp")
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
Set oRng = oDoc.Content
'先取消所有的文本的高亮
oRng.HighlightColorIndex = wdNoHighlight
sText = oRng.Text
'要查找的文本字符串
sFindText = "测试"
'文本字符串的长度
iLen = Len(sFindText)
If InStr(1, sText, sFindText) > 0 Then
With oRegExp
sPattern = sFindText
'设置是否匹配所有的符合项,True表示匹配所有, False表示仅匹配第一个符合项
.Global = True
'设置是否区分大小写,True表示不区分大小写, False表示区分大小写
.IgnoreCase = True
'设置要查找的正则规则
.Pattern = sPattern
'判断是否可以找到匹配的字符,若可以则返回True
Set oMatches = .Execute(sText)
For Each oMatch In oMatches
'返回匹配到的字符串的位置
iStart = oMatch.FirstIndex
Set oRng = oDoc.Range(iStart, iStart + iLen)
'将找到的字符串高亮
oRng.HighlightColorIndex = wdYellow
Next
End With
End If
End Sub


发表评论