Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
DiscussionsAccessExcelInfoPathOutlookPowerPointPublisherWord
DirectoryUser Groups
Related Topics
Outlook ExpressInternet ExplorerWindowsMS Server ProductsMore Topics ...

MS Office Forum / Word / Programming / September 2007

Tip: Looking for answers? Try searching our database.

search for two words in a sentance, and copy the words inbetween

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
OTWarrior - 26 Sep 2007 16:01 GMT
Say I have the sentance:

The cat sat on the mat

how would i search for
"The cat" & "the mat"
and copy the text inbetween (in this case: "sat on")

I know that to search for one word could be:

With Selection.Find
   .Text = "name"
End With

but I am a bit lost from there
fumei - 26 Sep 2007 17:04 GMT
Here is a possible way.  It works, but probably can be refined.  It does not
use Selection.

Sub HereKitty()
Dim r As Range
Dim j As Long
Dim k As Long

Set r = ActiveDocument.Range
With r.Find
  .ClearFormatting
  Do While .Execute(Findtext:="The cat", Forward:=True) = True
     j = r.End
     r.Expand unit:=wdSentence
     With r.Find
        If .Execute(Findtext:="the mat", _
           Forward:=True) = True Then
           k = r.Start
           MsgBox ActiveDocument.Range(Start:=j, _
              End:=k).Text
        End If
     End With
     r.Collapse Direction:=wdCollapseEnd
  Loop
End With
End Sub

What it does:

1.  makes a range of the document
2.  looks for "The cat"
3.  makes the variable j = .End of the Found range.  Remember, when Range is
used with Find the range itself changes to the Found parameters.  This is
important.  This makes j = the .End of "The cat"

4.  expands the Found range to to sentence.

eg.  The cat sat on the mat.  The Found makes  r = "The cat" range.  The
Expands makes it "The cat sat on the mat."

5.  does a Find in THAT range for "the mat"
6.  if Found, that makes r now = the range of "the mat".  The variable k = .
Start - ie.  the value at the start of "the mat"
7.  now we have the END of "The cat" (ie. j) , and the START of "the mat" (ie.
k)
8.  Display whatever is between those in messagebox - but you could do
whatever you want with it).
9.  collapse r.  IMPORTANT!  Otherwise it gets stuck in a loop.

Example:

The cat sat on the mat.

The cat purred its way across the mat.

The code will display:

"on the"

"purred its way across "

I used the Expand to the Sentence, as that seems to be what you want.  It
could be adjusted.

Rate this thread:






 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.