使用 VBA 宏删除 PowerPoint 中的图片

use*_*496 6 powerpoint vba image

我正在使用以下 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
Run Code Online (Sandbox Code Playgroud)

该代码删除了部分但不是全部图片。运行该代码3次后,所有图片都被删除。我哪里出错了?请告诉我

Dav*_*ens 6

从集合中删除项目时,您必须使用不同的迭代。

尝试这个:

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
Run Code Online (Sandbox Code Playgroud)

这是因为当删除项目时,集合会重新索引,因此,如果您删除Shapes(2),则删除后先前的内容Shapes(3)将变为Shapes(2),并且会被循环有效地“跳过”。为了避免这种情况,您必须从最后一个形状开始,然后按相反的顺序删除它们。