Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I search for a particular word in a document? 1

Status
Not open for further replies.

nesplb

Programmer
Jul 29, 2003
109
NO
Hi!
I want to search for a particular word in a MS word document. I don't want to search from the beginning of the text, but from the place the insertionpoint is and "upwards". I want to stop the search when I find the particular word...
Does anyone know how to do this?
 
Hi nesplb,

Have you tried doing it with the Word Find dialog and recoording a macro while you do it? I did and I got ..

Code:
Sub Macro12()
Code:
'
' Macro12 Macro
' Macro recorded 04/08/03 by Tony Jollans
'
Code:
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "asd"
        .Replacement.Text = ""
        .Forward = False
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
End Sub

If you add a check on Selection.Find.Found after it you will be able to tell whether the Find was successful or not.

Enjoy,
Tony
 
Thank you very much!:) I give you a star for this one as well;)
The search works great! As you might have noticed, the insertionpoint moves up to the searchstring and marks it if the search is succesful. Do you know how I can avoid that, so the insertionpoint stays at the same place it originally was?

 
Hi nesplb,

When you search with Selection the Selection (i.e Insertion Point) is moved to where the Find ends.

You can search with a Range instead, but you will then have to work with the range afterwards to do anything as a result of the Find. This code just displays a message - change it to do what you want.

Code:
Dim tjRange As Range
Set tjRange = Selection.Range

tjRange.Find.ClearFormatting
With tjRange.Find
    .Text = "abcde"
    .Replacement.Text = ""
    .Forward = False
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
tjRange.Find.Execute
If tjRange.Find.Found Then
    MsgBox "Found at position " & tjRange.start & " through " & tjRange.End
Else
    MsgBox "Not Found"
End If

Enjoy,
Tony
 
Thank you very much!
Your help is very much appreciated!!:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top