Powerpoint VBA Loop不会循环遍历所有幻灯片

时间:2015-08-28 07:34:16

标签: vba loops powerpoint powerpoint-vba shapes

有点问题,我有一些VBA代码遍历我的ppt中的所有工作表,循环遍历每个ppt中的所有形状,如果找不到特定的文本字符串,则删除ppt。除了代码似乎无缘无故地停止循环似乎工作得很好。我必须按F5大约4次才能使代码循环遍历所有工作表。它可能与我的代码有关,所以我想我会首先尝试Stackoverflow的好人。

Public Sub ExportMBR()
Dim oSld As Slide
Dim oShp As Shape
Dim strSearch As String
Dim i As Integer

strSearch = "R&T MBR"
i = 0

For Each oSld In ActivePresentation.Slides
    Debug.Print (ActivePresentation.Slides.Count)
    Debug.Print (oSld.Name)
    For Each oShp In oSld.Shapes
        If oShp.HasTextFrame Then
            If oShp.TextFrame.TextRange.Find(strSearch) Is Nothing Then
            Else
                Debug.Print (oSld.Name & " Slide found")
                i = i + 1
            End If
        End If
    Next oShp
    If i = 0 Then
        Debug.Print (oSld.Name & " Deleting")
        oSld.Delete
        i = 0
    End If
    i = 0
Next oSld

myQ = "<afilepath>"
myName = myQ & "<anameformat>") & ".pptx"
ActivePresentation.SaveCopyAs myName

Call Shell("explorer.exe " & myQ, vbNormalFocus)

End Sub

我的ppt中有34张幻灯片,每次运行将循环通过大约7张幻灯片正确识别并删除我不需要的幻灯片,但是没有任何错误,它将停止循环并继续执行其余代码。如果这有所不同,则在幻灯片17和18上找到该字符串。我添加了一些额外的功能来尝试解决问题,如debug.prints和i = 0,但我无法弄清楚我做错了什么。

非常感谢提前!

PPW

2 个答案:

答案 0 :(得分:2)

当您循环遍历该集合中的每个对象时,无论何时删除集合中的任何对象,都需要向后计数。因此,在这些情况下,您不能使用For Each oSld In ActivePresentation.Slides语句,而是执行此操作:

Dim lCntr as Long
Dim oSld as Slide
For lCntr = ActivePresentation.Slides.Count to 1 Step -1
  Set oSld = ActivePresentation.Slides(lCntr)
  ' Do your stuff here...
  Set oSld = Nothing
Next

http://youpresent.co.uk

下载更多免费的PowerPoint宏和加载项

答案 1 :(得分:1)

因为Find(strSearch)&amp; oSld.Delete处于同一循环,你需要将它们分开!  解决您想要首先进行del的幻灯片,然后对其进行删除。

例如:假设您有slide_1&amp; slide_2&amp; slide_3你想要del slide_1&amp; slide_2&amp; slide_3。实际上,你的VBA只有del slide_1&amp; slide_3。

在循环For Each oSld In ActivePresentation.Slides中,查找序列应为slide_1 =&gt; slide_2 =&gt; slide_3。但是,第一个循环周期将del slide_1,其余幻灯片计数变为2(sli​​de_2&amp; slide_3),因此第二个循环周期将从slide_3开始。这就是原因。