使用 VBA 宏删除 PowerPoint 中的图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19588567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:02:54  来源:igfitidea点击:

Delete pictures in PowerPoint using VBA macro

imagevbapowerpoint

提问by user2862496

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

我正在使用以下 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

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

此代码删除了一些但不是全部图片。运行此代码3次后,所有图片都被删除。我哪里出错了?请让我知道

采纳答案by David Zemens

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 lastshape, and delete them in reverse order.

这是因为集合是重新建立索引时,被删除的项目,因此,如果您删除Shapes(2)那么什么是以前Shapes(3)变得Shapes(2)删除后,并有效地循环“跳过”。为避免这种情况,您必须从最后一个形状开始,并以相反的顺序删除它们。