VBA Powerpoint:删除具有特定文本的形状。运行时错误' -2147024809(80070057)':指定的值超出范围

时间:2016-10-21 09:25:37

标签: vba powerpoint-vba powerpoint-2010

我有一个很长的ppt演示文稿(大约850张幻灯片),后半部分充满了我想要删除的某些文字的形状。可悲的是,它似乎与Slide Master无关,所以我无法使用它。

我收到了一个错误:

Run-time error '-2147024809 (80070057)': 
The specified value is out of range

这是我现在得到的代码

Sub DeleteShapeWithSpecTxt()


Dim oSl As Slides, oSh As Shapes, oTr As TextRange
Dim str As String
Dim testcomp1, testcomp2
Dim lppt, ShapeNb, k, j As Long
Dim pptAct
Set pptAct = PowerPoint.ActivePresentation


str = pptAct.Slides(335).Shapes(4).TextFrame.TextRange.Text
lppt = pptAct.Slides.Count




For k = 1 To lppt
    ShapeNb = pptAct.Slides(k).Shapes.Count
    For j = 1 To ShapeNb
        If pptAct.Slides(k).Shapes(j).HasTextFrame And StrComp(str, pptAct.Slides(k).Shapes(j).TextFrame.TextRange.Text) = 0 Then
            pptAct.Slides(k).Shapes(j).Delete
        End If
    Next
Next

End Sub

2 个答案:

答案 0 :(得分:1)

此代码可能会引发错误的原因有多种。首先,如果幻灯片335或形状4不存在(尝试使这些数字动态或处理错误)。接下来,你的If行将评估这两个部分,所以如果形状没有TextFrame,VBA仍会尝试评估第二部分,从而引发错误。最后,您还需要在可能删除对象的任何对象集合中向后计数。您还可以使用For Each Next构造简化此操作,并可选择将搜索文本传递给主代码中的过程:

Sub DeleteShapeWithSpecTxt(Optional sSearch As String)
  Dim oSld As Slide
  Dim oShp As Shape
  Dim lShp As Long

  On Error GoTo errorhandler
  If sSearch = "" Then sSearch = ActivePresentation.Slides(335).Shapes(4).TextFrame.TextRange.Text

  For Each oSld In ActivePresentation.Slides
    ' I would usually use the next line to loop through all shapes on the slide but can't in this case as shapes may be deleted
    'For Each oShp In oSld.Shapes
    For lShp = oSld.Shapes.Count To 1 Step -1
      With oSld.Shapes(lShp)
        If .HasTextFrame Then
          If StrComp(sSearch, .TextFrame.TextRange.Text) = 0 Then .Delete
        End If
      End With
    Next
  Next
Exit Sub
errorhandler:
  Debug.Print "Error in DeleteShapeWithSpecTxt : " & Err & ": " & Err.Description
  On Error GoTo 0
End Sub

如果您想使搜索文本动态化,这是一个很好的简单方法。只需将如果sSearch ="" ... 替换为:

If sSearch = "" Then sSearch = InputBox("Enter test to search for and all shapes matching the text will be deleted across this presentation:","Delete Matching Shapes","test")

答案 1 :(得分:0)

@JamieG谢谢,我找到了相同的解决方案(但不像你的代码那样整洁)。当我看到你的回答时我会发布它

干杯

编辑:更精确:字符串的动态设置有点困难(我对VBA的了解不是很先进)。因此,我选择某个幻灯片/形状的文本要容易得多。 对IF的评论是关键,以及删除时的向后计数