Word VBA查找并突出显示匹配项

时间:2011-03-16 06:27:47

标签: vba ms-word word-vba

我有以下代码已经工作但仍需要进行微调。它是一个找到通配符搜索字符串匹配并突出显示的函数。但我相信它仍然可以使用替换全部在一行中完成。我已经尝试了几乎所有我能想到的东西,我认为是时候向专家们询问了这一点。请告诉我如何以更短的方式完成这项工作。任何帮助将不胜感激。谢谢!

Sub findfunction()
If (findHL(activedocument.Range, "[aeiou]")) = True Then MsgBox "Highlight vowels Done", vbInformation + vbOKOnly, "Vowels Highlight Result"
End Sub

Function findHL(r As Range, s As String) As Boolean
Dim rdup As Range
Set rdup = r.Duplicate
rdup.Find.Wrap = wdFindStop

Do While rdup.Find.Execute(findtext:=s, MatchWildcards:=True) = True
   If (Not rdup.InRange(r)) Then Exit Do
   rdup.HighlightColorIndex = wdBlue
   rdup.Collapse wdCollapseEnd
Loop

findHL = True
End Function

2 个答案:

答案 0 :(得分:2)

隐藏在google内部非常深的地方:

Options.DefaultHighlightColorIndex = wdYellow

Selection.find.HitHighlight( string ) 

答案 1 :(得分:0)

我设法找到了自己的解决方案做了几次试验。这是我的解决方案,仅供参考其他可能正在为我之前的问题寻找相同解决方案的人提供:

Sub findfunction()
If (findHL(activedocument.Content, "[aeiou]")) = True Then MsgBox "Highlight vowels Done", vbInformation + vbOKOnly, "Vowels Highlight Result"
End Sub

Function findHL(r As Range, s As String) As Boolean
Options.DefaultHighlightColorIndex = wdBlue
r.Find.Replacement.highlight = True
r.Find.Execute FindText:=s, MatchWildcards:=True, Wrap:=wdFindContinue, Format:=True,  replacewith:="", replace:=wdReplaceAll
findHL = True
End Function

简单但它将我之前的代码删除了几行。