Search code examples
vbamethodsms-wordfind

How does .Find.Execute method work in MS Word files?


I know it is a very basic question, but I still can't quite understand how .Find.Execute method works in MS Word files.

For example, I see a lot of codes with this snippet

Selection.Find.Execute FindText:="some text"
     Do While Selection.Find.Found         
         Selection.Find.Execute
     Loop

My basic questions are:

1- Is there a difference between using .Find.Text and .Find.Execute FindText?

2- Why is the while loop Do While Selection.Find.Found used instead of using If Selection.Find.Found ? Or what does it mean?

3- What is the meaning of Selection.Find.Execute? And what is its role at the end of the while loop?


Solution

  • I have already posted an answer to one of your questions showing how to use that approach. In any event, using Selection is both inefficient and liable to produce excessive screen flicker. Moreover, unless you collapse the found range, you're liable to end up with an endless loop.

    The following three approaches are functionally equivalent:

    Sub Demo1()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      With .Find
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = True
        .Text = "<[ACEMR]{3}[1-4][1-9]{2}>"
        .Replacement.Text = ""
      End With
      Do While .Find.Execute = True
        'Do whatever with the found range
        MsgBox .Text
       .Collapse wdCollapseEnd
      Loop
    End With
    Application.ScreenUpdating = True
    End Sub
    
    Sub Demo2()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      With .Find
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = True
        .Text = "<[ACEMR]{3}[1-4][1-9]{2}>"
        .Replacement.Text = ""
        .Execute
      End With
      Do While .Find.Found = True
        'Do whatever with the found range
        MsgBox .Text
       .Collapse wdCollapseEnd
       .Find.Execute
      Loop
    End With
    Application.ScreenUpdating = True
    End Sub
    
    Sub Demo3()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      With .Find
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = True
        .Text = "<[ACEMR]{3}[1-4][1-9]{2}>"
        .Replacement.Text = ""
        .Execute
        Do While .Found = True
          'Do whatever with the found range
          With .Parent
            MsgBox .Text
            .Collapse wdCollapseEnd
            .Find.Execute
          End With
        Loop
      End With
    End With
    Application.ScreenUpdating = True
    End Sub