我正在使用以下VBA宏删除PowerPoint幻灯片中的所有图片:
Public Function delete_slide_object(slide_no)
' Reference existing instance of PowerPoint
Set PPApp = GetObject(, "Powerpoint.Application")
' Reference active presentation
Set PPPres = PPApp.ActivePresentation
' Delete object in slide
Set PPSlide = PPPres.Slides(slide_no)
For Each PPShape In PPSlide.Shapes
If PPShape.Type = msoPicture Then
PPShape.Delete
End If
Next PPShape
Set PPShape = Nothing
Set PPSlide = Nothing
Set PPPres = Nothing
End Function
此代码正在删除部分但不是全部图片。运行此代码3次后,所有图片都将被删除。我哪里错了?请让我知道
答案 0 :(得分:3)
从集合中删除项目时,必须使用不同的迭代。
试试这个:
Dim p as Long
For p = PPSlide.Shapes.Count to 1 Step -1
Set PPShape = PPSlide.Shapes(p)
If PPShape.Type = msoPicture Then PPShape.Delete
Next
这是因为在删除项目时会对集合进行重新编制索引,因此如果删除Shapes(2)
,则删除后Shapes(3)
之前的内容会变为Shapes(2)
,并且有效#&# 34;跳过的"通过循环。为避免这种情况,您必须从 last 形状开始,并以相反的顺序删除它们。