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

  • Thread starter OTWarrior via OfficeKB.com
  • Start date
O

OTWarrior via OfficeKB.com

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
 
F

fumei via OfficeKB.com

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top