Search code examples
vbapowerpoint

Powerpoint VBA Macro to send only Rectangles to back


I'm trying to create a macro that can send to back the "Rectangle" shapes in my current selection (which can have either Rectangle shapes or Pictures). I was trying to create one with an "IF" condition that checks if the shape is a picture or not, and if it's not then it will send the shape to the back. It works fine as long as there is only one object selected, but my goal is to select both Rectangles and Pictures at the same time, and then let the macro go through all of them and send only Rectangles to the back. I thought I had it, but the macro I tried does nothing.

The failed attempt below:

Dim oSh as Shape

For Each oSh In ActiveWindow.Selection.ShapeRange
If oSh.Type <> msoPicture Then
ActiveWindow.Selection.ShapeRange.ZOrder msoSendToBack
ElseIf oSh.Type = msoPicture Then
ActiveWindow.Selection.ShapeRange.ZOrder msoBringToFront
    
      End If
      
    Next oSh

Solution

  • You are close - the only issue you have it that with ActiveWindow.Selection.ShapeRange.ZOrder msoSendToBack you send all shapes in the selection to back (same for front). Simply use oSh.ZOrder msoSendToBack to handle the shapes individually.

    Note that your condition for the Else is not needed - the shape type is either a Picture or not (I have reverted the first if condition for better readability).

    Dim oSh As Shape
    For Each oSh In ActiveWindow.Selection.ShapeRange
        If oSh.Type = msoPicture Then
            oSh.ZOrder msoBringToFront
        Else
            oSh.ZOrder msoSendToBack
        End If
    Next oSh
    

    If you want to handle all shapes of the current slide (without the need to select them first), change the For-Loop to

    For Each oSh In Application.ActiveWindow.View.Slide.Shapes