Cymro
Cymro

Reputation: 1302

VBA For each - loop order

In VBA, it's possible to loop through shapes. For example:

For Each shp In slide.Shapes
 shp.top=0
Next

The question is, which parameter is being used to determine the order of the loop and how can this parameter be set?

Upvotes: 0

Views: 551

Answers (2)

Cymro
Cymro

Reputation: 1302

I found the answer on the MicroSoft site:

Shape.ZOrderPosition Property (PowerPoint)

The site says "A shape's position in the z-order corresponds to the shape's index number in the Shapes collection.".

I then did a short sort routine to set the z-order position based on the .top parameter of the shape:

For i = 2 To sld.Shapes.Count
  If sld.Shapes(i).Top < sld.Shapes(i - 1).Top _ 
  and sld.Shapes(i).ZOrderPosition > sld.Shapes(i - 1).ZOrderPosition Then_
  sld.Shapes(i).ZOrder msoSendBackward
Next i

Upvotes: 0

DisplayName
DisplayName

Reputation: 13386

edited after OP's clarification about his need of looping through shapes from the highest on the lowest

you can use SortedList object use Shape Top property as the SortedList key and the Shape object itself as its corresponding value:

Sub Main()
    Dim shp As Shape
    Dim j As Long

    With CreateObject("System.Collections.SortedList")
        For Each shp In slide.Shapes
            .Add shp.Top, shp
        Next

        For j = 0 To .Count - 1 'list shapes from the highest to the lowest
            MsgBox .GetByIndex(j).Name & " - " & .getkey(j)
        Next

    End With
End Sub

Upvotes: 1

Related Questions