We help IT Professionals succeed at work.

Get word text after search string

I'm stumped; I've played around and adapted the following from some code that I found here (thanks yall) and I can ALMOST get what I need, but not quite.

If you see the following text, I am trying to retrieve the paragraph that is after I have searched and found the common text "Purpose/scope:".  The code below selects all of it.  I'd like to copy the text either into field in another word doc, or into an access field, but for right now all I'm really concerned about is how to select and copy only paragraph following purpose/scope, not the entire section.

PURPOSE/SCOPE:      This procedure will provide the guidelines to assist the Technician in the shutdown of the Towers.

Here's my code:  (once again, "borrowed" from this site)

Sub searchtext()
    Dim rng As Range
    Dim para As Paragraph
    Dim sSearch$
   
   sSearch = "Purpose/Scope:"
   
    Set rng = ActiveDocument.Range
    With rng.Find
        .Execute Findtext:=sSearch
        Selection.MoveRight Unit:=wdWord, Count:=1
    End With
   
    Set para = rng.Paragraphs(1)
    Set rng = para.Range
       
    For Each para In rng.Paragraphs
      If Selection.Find.Execute(sSearch, Wrap:=wdWrapAlways) = True Then
        rng.Start = Selection.Range.Start
       rng.Expand Unit:=wdParagraph
   rng.Select
   rng.Copy
   Else
      MsgBox "Searchtext " & sSearch & " not found."
   End If
    Next para
End Sub

Thanks in advance!

Traci
Comment
Watch Question

Can you try something like this right after  "rng.Copy"?

I'm not very familiar with Word VBA so I can't tell if the Find method is valid on your "rng" object.  I've used this Find and Replace method a number of times in Macros though and it works well.  If it does, it should just delete the text "PURPOSE/SCOPE:" from the rng.

With rng.Find
   .Text = "PURPOSE/SCOPE:"
   .Replacement.Text = ""
   .Forward = True
   .Wrap = wdFindContinue
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
rng.Find.Execute Replace:=wdReplaceAll

Open in new window

GrahamSkanRetired
Top Expert 2012
Commented:
Try it like this
Sub searchtext()
    Dim rng As Range
    Dim para As Paragraph
    Dim sSearch$
    
    sSearch = "Purpose/Scope:"
    
    Set rng = ActiveDocument.Range
    If rng.Find.Execute(sSearch) Then
        rng.Expand wdParagraph
        rng.Collapse wdCollapseEnd
        rng.Expand wdParagraph
        rng.Copy
        '...
    Else
        MsgBox "Searchtext " & sSearch & " not found."
    End If
End Sub

Open in new window

Author

Commented:
Thanks to you both!

CitizenRon - your code helped me to get rid of the Purpose/Scope: text

Graham Skan - yours helped me to get to the piece I needed to copy behind the text.
I need to tweak it a little more, then I'll post the finished result.  Thanks again for the quick responses!

Traci