Thanh Tung Doan
Thanh Tung Doan

Reputation: 1

Delete the same shapes in each slides

I have many PPT files, each PPT file has many slides and in each slides, there are many shapes.i want to delete the 2 shapes with the name "Google Shape;227;p3" and "Google Shape;228;p3" in each slide respectively.

i tried 2 macros differently for each shape like

Sub DeleteLogo()
    Dim n As Integer
    Dim shp As Shape
    Dim sld As Slide

    For n = 1 To ActivePresentation.Slides.Count
        For Each shp In ActivePresentation.Slides(n).Shapes
            If shp.Name = "Google Shape;227;p3" Then shp.Delete
        Next
    Next n
End Sub

and it worked fine for 1 shape only, but when i tried to combine to delete 2 shapes in the same macro like

Sub DeleteLogo()
    Dim n As Integer
    Dim shp As Shape
    Dim sld As Slide

    For n = 1 To ActivePresentation.Slides.Count
        For Each shp In ActivePresentation.Slides(n).Shapes
            If shp.Name = "Google Shape;227;p3" Then shp.Delete
            If shp.Name = "Google Shape;228;p3" Then shp.Delete
        Next
    Next n
End Sub

it failed and said

enter image description here where does the logic go wrong ? please help.

explanation for illogical code

Upvotes: 0

Views: 9

Answers (1)

Hasan Raza
Hasan Raza

Reputation: 525

Problem : second macro arises because the loop gets disrupted when you delete a shape.

Solution : iterate through the Shapes collection in reverse order

Sub DeleteLogo()
    Dim n As Integer
    Dim shp As Shape
    Dim sld As Slide
    Dim i As Integer

    For n = 1 To ActivePresentation.Slides.Count
        Set sld = ActivePresentation.Slides(n)

        
        For i = sld.Shapes.Count To 1 Step -1
            Set shp = sld.Shapes(i)
           
            If shp.Name = "Google Shape;227;p3" Or shp.Name = "Google Shape;228;p3" Then
                shp.Delete
            End If
        Next i
    Next n
End Sub

Upvotes: 0

Related Questions