我有一个 Word 宏,是我之前从别人的宏中定制的(不幸的是,我找不到源码)。目的是用青绿色突出显示所有出现的“他”和“他的”,用粉红色突出显示所有出现的“她”和“她的”。它部分起作用——它确实用青绿色突出显示“他”(而不是“他的”),用粉红色突出显示“她”(而不是“她的”)。
我究竟做错了什么?
Sub HighLightHeShe()
Dim vFindText As Variant
Dim oRng As Range
Dim i As Long
vFindText = Array("he", "his")
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
Do While .Execute(FindText:=vFindText(i), _
MatchWholeWord:=True, _
Forward:=True, _
Wrap:=wdFindStop) = True
oRng.HighlightColorIndex = wdTurquoise
oRng.Collapse wdCollapseEnd
Loop
End With
vFindText = Array("she", "her")
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
Do While .Execute(FindText:=vFindText(i), _
MatchWholeWord:=True, _
Forward:=True, _
Wrap:=wdFindStop) = True
oRng.HighlightColorIndex = wdPink
oRng.Collapse wdCollapseEnd
Loop
End With
lbl_Exit:
Exit Sub
End Sub
答案1
您之所以只查找每个数组中的第一个项,是因为您没有更改“i”的值。您需要将“Finds”包装在循环中。
见下文 ...
Sub HighLightHeShe()
Dim vFindText As Variant
Dim oRng As Range
Dim i As Long
vFindText = Array("he", "his")
For i = 0 To UBound(vFindText)
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
Do While .Execute(FindText:=vFindText(i), _
MatchWholeWord:=True, _
Forward:=True, _
Wrap:=wdFindStop) = True
oRng.HighlightColorIndex = wdTurquoise
oRng.Collapse wdCollapseEnd
Loop
End With
Next
vFindText = Array("she", "her")
For i = 0 To UBound(vFindText)
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
Do While .Execute(FindText:=vFindText(i), _
MatchWholeWord:=True, _
Forward:=True, _
Wrap:=wdFindStop) = True
oRng.HighlightColorIndex = wdPink
oRng.Collapse wdCollapseEnd
Loop
End With
Next
lbl_Exit:
Exit Sub
End Sub