PDA

View Full Version : [SOLVED:] Loop through shapes on current page



kkkwj
07-11-2018, 06:58 PM
Is there a way to loop through the shapes on only the current page of a Word document? I can get the current page number, and I know how to loop through all pages and shapes in the document. But I only want to work with a single page in the middle of the document. Probably I'll have to loop through all shapes and ask each shape what page it is on. Maybe an algorithm like this would work?


get and save the current page number
loop through all shapes in the document
select each shape in turn (and hope that resets the current page?)
use selection.Information() to get the current page number of the selected shape
(or use Shape.Anchor.Information(wdActiveEndPageNumber))

If the page numbers match
- then this shape is on the original current page


UPDATE: Yes, this algorithm worked fine. Here's a bit of code:


curpage = selection.Information(wdActiveEndPageNumber)
For Each shp In doc.shapes
shapepage = shp.Anchor.Information(wdActiveEndPageNumber)
If curpage = shapepage Then
' do your thing with the shape on the original current page
End If
Next

gmaxey
07-11-2018, 07:23 PM
Why not just:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey, http://gregmaxey.com/word_tips.html, 7/11/2018
Dim shp As Shape
For Each shp In ActiveDocument.Shapes
If shp.Anchor.Information(wdActiveEndPageNumber) = Selection.Information(wdActiveEndPageNumber) Then
'Work with the shape
End If
Next
lbl_Exit:
Exit Sub
End Sub

kkkwj
07-11-2018, 07:34 PM
Yes, that would work fine too. Is it necessary to loop through ALL shapes to find only the shapes on the current page? In other words, are shapes stored in the shapes collection in page order? (If they were, I could exit the loop early when shp.page > selection.page (so to speak).

macropod
07-11-2018, 11:09 PM
Try:

Sub Demo()
Dim Rng As Range, Shp As Shape
Set Rng = Selection.Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\page")
For Each Shp In Rng.ShapeRange
' do your thing with the shape
Next
End Sub

kkkwj
07-12-2018, 07:09 AM
Hi Paul, it's too funny that you post your code with the shapes organized by a page range. In my original post, I had a sentence wondering if shapes were organized by pages internally - then I could go straight to the shapes that I needed. But I removed the sentence because I thought, "No way that would be true." But apparently, they are... Thank you! Cheers, Kevin

macropod
07-12-2018, 07:44 AM
In my original post, I had a sentence wondering if shapes were organized by pages internally - then I could go straight to the shapes that I needed. But I removed the sentence because I thought, "No way that would be true." But apparently, they are...
They're not organised by page … but you can find what objects are on a page.