Delete pictures in PowerPoint using VBA macro

*爱你&永不变心* 提交于 2020-01-04 02:00:07

问题


I am using the following VBA Macro to delete all the pictures in a PowerPoint slide:

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

This code is deleting some but not all the pictures.After running this code 3 times , all the pictures get deleted. Where am i going wrong? Kindly let me know


回答1:


When deleting items from a collection, you have to use a different iteration.

Try this:

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

This is because the collection is re-indexed when items are removed, so if you delete Shapes(2) then what was previously Shapes(3) becomes Shapes(2) after the deletion, and is effectively "skipped" by the loop. To avoid this, you have to start with the last shape, and delete them in reverse order.



来源:https://stackoverflow.com/questions/19588567/delete-pictures-in-powerpoint-using-vba-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!