vbams-wordword-2007word-2003

Find text after using Selection.Extend function


I have used Selection.Extend to make selection of particular text from Start to End Now Text is in selection from the following code:

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

after selection I want to find "ABCD" in Selected text by the following code:

   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

but instead of finding it is Extending the selection to ABCD where ever it finds.

so my question is how do i escape from previous selection and selection.Find.Execute the ABCD within Start and End?


Solution

  • I think there's some misunderstanding about what Selection.Extend actually does, you might want to read up on it in the Language Reference. It emulates a keyboard command in the UI that extends the current selection by pre-defined "jumps".

    From your description, I understand that you want to locate the first search term in the document ("Start"). If it's present, search to the end of the document for the second search term ("End"). If that is also found, search between the two terms for the third search term.

    This is best done using three RANGES, one for each search term. Something like this:

    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