Changing search string in Find as move through a Word Document RRS feed

  • Question

  • I'm trying to write a macro to move through a document and locate words having a certain criteria.  For example, I first need to find a name having the format "[A-Z][a-z]{1,} [A-Z]{2,}" and later I need to find a serial number with the format "[0-9]{2}\/[0-9]{6]".  I can't simply use find to search for the name and the serial number from the beginning of the document without incorrectly locating the wrong information.  

    I need to first find the name and then continue searching from the location of the found name for the serial number.  If I search for the serial number from the beginning of the document there are other incorrect entries in the document that will be located.

    I have been able to find examples to find all the locations of a word in a document and I have tried using .Find.Execute using a range but have not been able to get it to work correctly.  I have searched this forums and others, but have not been able to find anything.  

    Thank you for all of your help!

    Monday, March 4, 2013 9:05 PM


  • Try this:

    Sub FindIt()
        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .Wrap = wdFindStop
            .MatchWildcards = True
            If .Execute(FindText:="[A-Z][a-z]{1,} [A-Z]{2,}") Then
                ' We found a name
                Selection.Collapse Direction:=wdCollapseEnd
                If .Execute(FindText:="[0-9]{2}\/[0-9]{6}") Then
                    ' We found a serial number
                    MsgBox "No serial number found!"
                End If
                MsgBox "No name found!"
            End If
        End With
    End Sub

    Regards, Hans Vogelaar

    • Marked as answer by Grant_S Tuesday, March 5, 2013 12:32 PM
    Monday, March 4, 2013 10:59 PM