Runaway Ranges

G

Greg Maxey

This may have been addressed before but I couldn't find anything with a
Google search of the VBA groups.

I can't seem to limit the range of a find operation to a single section of a
document (without using blunt force). To illustrated, create a new blank
document with three sections. In each section type the single word "Test."

Run this code:

Sub ScratchMacro()
Dim oRng As Range
Dim i As Long
Dim oCnt As Long
For i = 1 To ActiveDocument.Sections.Count
oCnt = 0
Set oRng = ActiveDocument.Sections(i).Range
With oRng.Find
.Text = "Test"
.Wrap = wdFindStop 'Makes no difference
While .Execute
'If oRng.InRange(ActiveDocument.Sections(i).Range) Then 'Blunt force
oCnt = oCnt + 1
'End If 'Blunt force
Wend
End With
MsgBox "Found " & oCnt & " times in Section " & i
Next i
End Sub

With the "Blunt force" lines stetted out the macro returns 3, 2, then 1 vice
the expected 1, 1, and 1.

Why is oRng being expanded beyond the "Set" scope?

Thanks.
 
J

Janine

Hi Greg
I ran your test and get that result.
But I just ran it in my 462 page document full of bits and pieces on screen
and it has no section breaks and it said "Found 39 times in Section 1"
Then I stuck a section break at end of document and no text after it.
"Found 39 times in Section 1 OK 0 times Section 2 OK"
 
G

Greg Maxey

Janine,

Thanks for confirming.

"Found 39 times in Section 1 OK 0 times Section 2 OK"

Yes, think that would be expected. As all instances are physically in
section 1 and there are no instances physically in section 2 or in keeping
with the observed behavior, all instances in the starting section to the end
of the document are found and reported.. What happens when you insert the
test word one or more times in section 2? Is the report for section 1
still correct or erroneous?
 
J

Janine

Greg, sorry I was just testing in 2010 and forgot to say it was 2010.

Glad you know it's not you and it's just a bug..



Greg Maxey said:
Janine,

Thanks for confirming.
 

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