遍历段落VBA中的每个单词

问题描述 投票:0回答:1

我想遍历段落中的每个单词,我编写代码:

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

但是,我觉得可以更简洁,还有其他更好的方法吗?

vba word-vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.