Reputation: 33672
I have an Excel file that servs as a DB. After sorting and modifying the data in the Excel file, I am copying the updated data to a PowerPoint Slide. Before copying all chart objects from the updated worksheet, I want to delete the old charts from the PowerPoint Slide.
I have used the piece of code below, however, I am getting an error message when trying to delete the last Chart in the Slide. The error message is "Shapes.Item: Integer out of range. 25 is not Index's valid range of 1 to 24".
Dim SlideNum, i As Integer
SlideNum = ActiveSheet.Cells(5, 2)
For i = 1 To PPT.ActivePresentation.Slides(SlideNum).Shapes.Count
' if current slide object is a chart, delete it
If PPT.ActivePresentation.Slides(SlideNum).Shapes.Item(i).HasChart Then
PPT.ActivePresentation.Slides(SlideNum).Shapes.Item(i).Delete
End If
Next i
Upvotes: 0
Views: 455
Reputation: 2979
Whenever you are looping through a collection of objects in VBA with the intention of deleting one or more of them you need to count backwards with Step -1 so your loop should start like this:
For i = PPT.ActivePresentation.Slides(SlideNum).Shapes.Count to 1 Step -1
Upvotes: 2