Problem searching for text in a range

S

Simon Woods

Hi

I have this code

'set leftmost, rightmost, topmost, bottommost positions to extremes
l_fLeft = m_oWordDoc.PageSetup.PageWidth
l_fTop = m_oWordDoc.PageSetup.PageHeight
l_fRight = 0
l_fBottom = 0

Debug.Print p_oRange.Text

Do While Not l_bFinished
p_oRange.Find.Execute vbCr, Forward:=True
If p_oRange.Find.Found Then
Debug.Print p_oRange.Start & " : " & p_oRange.End,
p_oRange.Information(wdHorizontalPositionRelativeToPage) & " : " & _
p_oRange.Information(wdVerticalPositionRelativeToPage)
Checksize p_oRange, l_fLeft, l_fTop, l_fRight, l_fBottom
Else
l_bFinished = True
End If
Loop

I'm trying to find all vbCr characters in the range I'm passing in and find
the rightmost and bottommost vbCr's. (Actually I'm trying to get the left,
top, right, bottom dimensions of the range and this was the only way I could
think about doing it.)

The range is subsection of a word document.

Debug.Print p_oRange.Text
41123456
My Full Name
My Address Line 1
My Address Line 2
Town
City
County
Postcode

Debug.Print p_oRange.Characters.Count
84

When I run through this loop, it seems to be searching beyond the end of the
range being passed in. Here's the result of the debug.print statement in the
middle of the loop

10 : 11 180.75 : 72
24 : 25 162.75 : 112.5
42 : 43 183 : 126.75
60 : 61 167.25 : 140.25
65 : 66 117.75 : 151.5
70 : 71 111 : 165.75
77 : 78 126 : 179.25
88 : 89 143.25 : 193.5 <=== *
106 : 107 250.5 : 207 <=== *

*These values are beyond the end of the range I passed in and I can only
assume they are the next vbCr's in the document.

What am I doing wrong? I thought that the Find.Execute would be restricted
to look between the start and end of the range? Have I misunderstood?

Thanks

Simon
 
K

Klaus Linke

Hi Simon,

After you Execute, the range is set to the matched text.

You need something like

Dim oRangeOld as Range
Set oRangeOld = p_oRange.Duplicate

Do While Not l_bFinished
p_oRange.Find.Execute vbCr, Forward:=True
If p_oRange.Find.Found Then
' ...
p_oRange.Collapse(wdCollapseEnd)
p_oRange.End=oRangeOld.End
Else
l_bFinished = True
End If
Loop

Or, since Execute returns True if some match was found, you could do without
l_bFinished, and re-write the code to something like "Do While .Execute(...)
Loop"

Regards,
Klaus
 
S

Simon Woods

Klaus said:
Hi Simon,

After you Execute, the range is set to the matched text.

You need something like

Dim oRangeOld as Range
Set oRangeOld = p_oRange.Duplicate

Do While Not l_bFinished
p_oRange.Find.Execute vbCr, Forward:=True
If p_oRange.Find.Found Then
' ...
p_oRange.Collapse(wdCollapseEnd)
p_oRange.End=oRangeOld.End
Else
l_bFinished = True
End If
Loop

Or, since Execute returns True if some match was found, you could do
without l_bFinished, and re-write the code to something like "Do
While .Execute(...) Loop"

Regards,
Klaus

Excellent ... thanks Klaus
 
Top