Why Doesn't This Loop-within-a-Loop Work?

O

osirun

So what I'm trying to do is loop through all the frames in my
document, and see if they're on the same page as text with the style
"Heading 2". Here's the code:

Dim SrcRg As Range
Dim frm As frame

Set SrcRg = ActiveDocument.Range

For Each frm In ActiveDocument.Frames

With SrcRg.Find
..ClearFormatting
..Text = ""
..Format = True
..Style = ActiveDocument.Styles("Heading 2")
..Forward = True
..Wrap = wdFindStop

Do While .Execute
If SrcRg.Information(wdActiveEndAdjustedPageNumber) =
frm.Range.Information(wdActiveEndAdjustedPageNumber) Then
MsgBox SrcRg.Information(wdActiveEndAdjustedPageNumber)
Exit Do
End If
Loop

End With

Next

What I'd like this to do is loop through all the frames, and for each
one search through all the Heading 2's and, if it finds one on the
page that the frame is on, print out a message box accordingly. In
practice, it just prints out the first page that has a frame and a
Heading 2 on... and that's it.

Can anyone smart tell me what's going on here?
 
J

Jay Freedman

This is just an educated guess...

When you call SrcRg.Find.Execute the first time, and it finds a Heading 2, the
location of SrcRg is changed to the location of the Heading 2. Every other time
through the outer For loop, the Find is executed on that SrcRg location -- so it
finds only the Heading 2 that it found the first time, which isn't on the same
page with any of the other frames. Therefore, none of the other pages print.

To fix this in a simple fashion, you could move the "Set SrcRg" line to be
_after_ the "For Each frm" line. Then for each frame the heading search will
start again at the beginning of the document and search to the correct heading.

Actually, this is a rather inefficient way to go about it. Presumably each frame
occurs somewhere in the document after its predecessor, so each frame's search
should start just after the end of the preceding Heading 2. That way the code
doesn't have to test every Heading 2 from the beginning of the document on every
iteration of the For Each loop.

To do this, leave the "Set SrcRg" line where it is. Instead, between the "End
With" and the "Next" add this line:

Set SrcRg = ActiveDocument.Range(Start:=SrcRg.End + 1, _
End:=ActiveDocument.Range.End)

(Caveat: Not tested, may need some tweaking!)

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so all
may benefit.
 
O

osirun

Thanks Jay! I ran into problems with the second, more efficient
solution, but the first idea worked like a charm. I'm just relieved
to get something that works at all... and starting to understand how
VBA works a little better :)
 

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