1

I'm trying to copy paste shape by using VBA in PowerPoint.
This code can't exit from If...End If statement.
What's wrong with my code?

Sub pasteshape()
    Dim oSl As Slide
    Dim oSh As Shape
        For Each oSl In ActivePresentation.Slides
        For Each oSh In oSl.Shapes    
            If oSh.Fill.Type = msoFillSolid Then
               oSh.Duplicate
            End If
        Next
        Next
End Sub
3
  • Can you please clarify what you mean by __ This code can't exit from If...End If statement__? Perhaps you need and Else clause? Commented Aug 28, 2017 at 20:56
  • 1
    @ainwood the Shapes collection is being added to, every time a solid-fill shape is encountered. The loop is infinite as written. Commented Aug 28, 2017 at 21:10
  • Ah - good point. Commented Aug 28, 2017 at 21:16

1 Answer 1

3

You're changing the collection you're iterating, as you're iterating it; that's always a bad idea!

So you have an infinite loop, because every time you duplicate a shape, you effectively add a solid-fill shape to the oSl.Shapes collection, which is then a solid-fill shape that should be duplicated - right?

You need a way to separate the process of knowing which shapes to copy and that of copying solid-fill shapes.

Make a new collection:

Dim solidShapes As Collection
Set solidShapes = New Collection

Now iterate the slides and their shapes, but instead of copying right away, add them to that collection:

    For Each currentShape In currentSlide.Shapes    
        If currentShape.Fill.Type = msoFillSolid Then
           solidShapes.Add currentShape
        End If
    Next

Notice I'm using readable identifiers without Systems Hungarian (aka useless) prefixes (read that link! Especially if you're a firm believer of Hungarian Notation).

Now you can iterate the solidShapes collection, and .Duplicate every item in it.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I'm looking for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.