I have a few presentations with shapes I need to delete, with
Those shapes with specific .Name can be grouped (not in my code). I found code in stackoverflow and tried to modify it.
If there are no shapes with .Name = "Name1"
I get an Error
"Object does not exist"
on the line If .Name = "Name1" Or .Name = "Name2" Then
Sometimes the code works, and then, if there are a lot slides in the presentation, I have an error. When I test with a 1-slide presentation - no error.
I have an Error
"Object variable or With block variable not set"
I don't understand how to declare variable
Sub DeleteShapes()
Dim oSld As Slide
Dim oShp As Shape
Dim oshpGroup As Shape
Dim Y As Long
Dim L As Long
Dim str As String
For Each oSld In ActivePresentation.Slides
For L = oSld.Shapes.Count To 1 Step -1
With oSld.Shapes(L)
' Find shape by name and delete it
If .Name = "XXName1" Or .Name = "XXName2" Then
.Delete
End If
If .Name = "Name1" Or .Name = "Name2" Then
.Delete
End If
' Find shape by color and delete it
If oShp.Fill.ForeColor.RGB = RGB(0, 0, 0) Or _
oShp.Fill.ForeColor.RGB = RGB(1, 1, 1) Or _
oShp.Fill.ForeColor.RGB = RGB(2, 2, 2) Or _
oShp.Fill.ForeColor.RGB = RGB(3, 3, 3) Then
oShp.Delete
End If
End With
Next L
Next oSld
End Sub
You can't refer to a shape after you've deleted it (which you've done previously). Change your sequential If...End If, If...End If to If...ElseIf....ElseIf...End If. – @BigBen
My revised code:
Sub DeleteShapes() Dim oSld As Slide Dim oShp As Shape Dim L As Long For Each oSld In ActivePresentation.Slides For L = oSld.Shapes.Count To 1 Step -1 With oSld.Shapes(L) If .Name = "XXName1" Or .Name = "XXName2" Then .Delete ElseIf .Name = "Name1" Or .Name = "Name2" Then .Delete ElseIf .Fill.ForeColor.RGB = RGB(0, 0, 0) Then .Delete ElseIf .Fill.ForeColor.RGB = RGB(1, 1, 1) Then .Delete ElseIf .Fill.ForeColor.RGB = RGB(2, 2, 2) Then .Delete ElseIf .Fill.ForeColor.RGB = RGB(3, 3, 3) Then .Delete End If End With Next L Next oSld End Sub