我想遍历段落中的每个单词,我编写代码:
sub search_word_in_paragraph()
With selection.Find
.Text = "[A-Za-z]{2,}"
.MatchWildcards = True
Do
.Execute
If .Found Then
If selection.Range.Text = "and" Then
selection.Range.Case = wdLowerCase
Exit For
End If
End If
Loop Until selection.Range.Previous <> " "
selection.Range.Case = wdTitleWord
selection.HomeKey unit:=wdLine
End With
end sub
但是,我觉得可以更简洁,还有其他更好的方法吗?
答案 0 :(得分:2)
您可以使用For...Each
遍历段落中的字词。以下是一个示例。
Sub TraverseWords()
Dim rng As Range
Set rng = Selection.Paragraphs(1).Range
For Each wrd In rng.Words
If Trim(wrd) = "and" Then
wrd.Case = wdLowerCase
Exit For
End If
Next
End Sub