使用 Selection.Extend 函数后查找文本

Find text after using Selection.Extend function

我已经使用 Selection.Extend 选择了从 StartEnd 的特定文本,现在可以从以下代码中选择文本:

Selection.Find.ClearFormatting
        With Selection.Find
        .Text = "Start"
        .Forward = True
        .Wrap = wdFindStop
        End With
    Selection.Find.Execute
    If Selection.Find.Found = False Then
    Else

    Selection.Extend

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "End"
        .Forward = True
        .Wrap = wdFindStop
   End With
   Selection.Find.Execute
   End If

选择后,我想通过以下代码在选定文本中找到 "ABCD":

   Selection.Find.ClearFormatting
        With Selection.Find
            .Text = "ABCD"
            .Forward = True
            .Wrap = wdFindStop
        End With
    Selection.Find.Execute
    If Selection.Find.Found = True Then
    MsgBox ("Found")
    Else
    MsgBox ("Not Found")
    End If

但不是找到它而是将选择扩展到 ABCD 它找到的任何地方。

所以我的问题是如何从之前的选择和 selection.Find.Execute StartEnd 中的 ABCD 中逃脱?

我刚测试过,你是.WrapwdFindStop。光标位于查找的末尾,您正在查找 .Forward = True。由于你在最后,一直寻找到停止,它不会找到它。

测试文本为:

Start ABCD End

更改后我让它工作:

.Forward = True

.Forward = False

在你的 Selection.Find"ABCD"

编辑:

然后

If Selection.Find.Found = True Then
    Selection.Collapse wdCollapseEnd
    Selection.Expand wdWord
Else
    MsgBox("Not Found")
End If

我认为对 Selection.Extend 的实际作用存在一些误解,您可能需要阅读语言参考中的内容。它模拟 UI 中的键盘命令,通过预定义的 "jumps".

扩展当前选择

根据您的描述,我了解到您想在文档 ("Start") 中找到第一个搜索词。 如果存在,则搜索到文档末尾的第二个搜索词 ("End")。如果也找到了,则在这两个词之间搜索第三个搜索词。

最好使用三个范围,每个范围对应一个搜索词。像这样:

Dim rngStart as Word.Range, rngEnd as Word.Range, rngTarget as Word.Range
Dim bFound as Boolean
Set rngStart = ActiveDocument.Content
bFound = rngStart.Find.Execute(FindText:="Start", Forward:=True, Wrap:=wdFindStop)
If bFound Then
  Set rngEnd = rngStart.Duplicate
  bFound = rngEnd.Find.Execute(FindText:="End", Forward:=True, Wrap:=wdFindStop)
  If bFound Then
    rngStart.End = rngEnd.End 'Extend first Found to include second Found
    Set rngTarget = rngStart.Duplicate
    bFound = rngTarget.Find.Execute(FindText:="ABCD", Forward:=True, Wrap:=wdFindStop)
    If bFound Then
        MsgBox "Found"
    Else
        MsgBox "Not found"
    End If
  End If
End If