代码之家  ›  专栏  ›  技术社区  ›  ApexPolenta

如何获取Range。找到要停在范围的末尾吗?

  •  0
  • ApexPolenta  · 技术社区  · 1 年前

    在Word中定义了一个范围后,我试图删除该范围内出现的所有字符串。但是,“查找”功能会一直延续到文档的末尾。

    我将用一个玩具例子来说明这个问题。我设置了一个Word文档,其中包含以下文本:

    start of range
        a b c d e f
    end of range
    
    a b c d e f
    

    然后使用以下代码:

    Sub test()
    
        Dim r As Range
        
        Set r = ThisDocument.Content
        
        'Limit the range to between the start and end flags
        r.Find.Execute findtext:="start of range*end of range"
        
        'Delete all instances of "b". Intended to work only within the flags
        Do While r.Find.Execute(findtext:="b", replacewith:="", Wrap:=wdFindStop)
        Loop
    
    End Sub
    
    

    我希望此代码只删除 b 在标志中,但它最终删除了两者,尽管明确定义了 Wrap 要成为的参数 wdFindStop 。如何使Find函数停止在r的末尾?

    1 回复  |  直到 1 年前
        1
  •  1
  •   taller    1 年前
    • .Execute Replace:=wdReplaceAll 替换所有实例而不循环

    Microsoft文档:

    Find.Wrap property (Word)

    Find.Execute method (Word)

    Sub DelWords()
        Dim searchRng As Range, iEnd As Long
        iEnd = ActiveDocument.Paragraphs(4).Range.End
        With ActiveDocument.Range(0, iEnd).Find
            .ClearFormatting
            .Text = "b"
            .Forward = True
            .Wrap = wdFindStop '**
            With .Replacement
                .Text = ""
                .ClearFormatting
            End With
            .Execute Replace:=wdReplaceAll
        End With
        Application.ScreenUpdating = True
    End Sub
    

    enter image description here