我在一个长MS Word文档中搜索以ly
结尾并突出显示为黄色的单词。
但是,某些以ly
结尾的单词不是副词(仅限家庭),我想跳过这些。
如何修改我的代码逻辑来执行此操作:
If word=TargetList Then [If word=ExceptionList Then Skip ] Else [ highlight ]
是否需要过滤声明?
Sub FindAdverbs()
'
' FindAdverbs Macro
'
'
Dim range As range
Dim i As Long
Dim TargetList
TargetList = Array("ly") ' 'string to search for
ExceptionList = Array("family", "only") 'string of words to ignore
For i = 0 To UBound(TargetList)
Set range = ActiveDocument.range
With range.Find
.Text = TargetList(i)
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute(Forward:=True) = True
range.HighlightColorIndex = wdYellow
Loop
End With
Next
End Sub
答案 0 :(得分:0)
请尝试此代码。除了@Peh所说的使用保留字来命名变量之外,我避免使用变体。 MS Word是关于文本和文本包含在字符串中。在操作文本时,使用它们更容易,更有效。
Sub FindAdverbs()
' 03 Jun 2017
Dim Targets() As String
Dim Exceptions As String
Dim Rng As Range
Dim LastFound As Long, RngEnd As Long
Dim n As Long
Dim i As Long
Targets = Split("ly,lo", ",") 'string to search for
Exceptions = "family,only" 'string of words to ignore
For i = 0 To UBound(Targets)
Set Rng = ActiveDocument.Content
With Rng.Find
.Text = "*" & Targets(i)
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = True
.Format = False
.Forward = True
.MatchSoundsLike = False
.MatchAllWordForms = False
Do
.Execute
With Rng
If (.End <= LastFound) Then Exit Do
LastFound = .End
RngEnd = .End
.Collapse wdCollapseEnd
.MoveStart wdWord, -1
n = .MoveEndUntil(".,;:!?" & Chr(9) & Chr(10) & Chr(11) & Chr(12) & Chr(13) & Chr(32))
If (InStr(1, Exceptions, Trim(.Text), vbTextCompare) = 0) And (n = 1) Then
.HighlightColorIndex = wdYellow
End If
.SetRange RngEnd, RngEnd
End With
Loop While .Found
End With
Next i
End Sub
另一项值得你注意的改变是.Text = "*" & Targets(i)
行。这将确保搜索不会出现在末尾以外的位置包含“ly”的单词。