如何让 Range.Find 在范围末尾停止?

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

在 Word 中定义范围后,我尝试删除该范围内所有出现的字符串。然而,查找功能却继续到文档末尾。

我将用一个玩具示例来说明这个问题。我建立了一个包含以下文本的 Word 文档:

abcdefghij

然后使用此代码:

Sub test()

    Dim r As Range
    
    Set r = ThisDocument.Content
    
    'Limit the range to four characters in the middle of the document
    r.Find.Execute findtext:="cdef"
    
    'Delete all lowercase letters. Intended to only work on the characters within r
    Do While r.Find.Execute(findtext:="[a-z]", MatchWildcards:=True, replacewith:="", Wrap:=wdFindStop)
    Loop

End Sub

我希望这段代码只删除

cdef
,但尽管明确将
cdefghij
参数定义为
Wrap
,但它最终还是删除了
wdFindStop
。如何让Find函数停在r的末尾?

vba ms-word
1个回答
0
投票
Sub DelWordsWithWildCards()
    Application.ScreenUpdating = False
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Text = "<cdef>"  ' **
        .MatchWildcards = True  ' **
        .Forward = True
        .Wrap = wdFindContinue
        With .Replacement
            .Text = ""
            .ClearFormatting
        End With
        .Execute Replace:=wdReplaceAll
    End With
    Application.ScreenUpdating = True
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.