指定的值超出范围

时间:2018-09-23 15:11:07

标签: vba collections powerpoint presentation

我正在尝试显示幻灯片编号。如果它们甚至是一个带有红色字体单词的文本框,则在立即窗口中显示。但是以下错误不断弹出。有什么想法可以继续前进。

运行时错误'-2147024809(80070057) 指定的值超出范围。

代码:

Sub redfont()

    Dim sld As Slide
    Dim shp As Shape
    Dim x As Byte
    Dim z, i

    With ActivePresentation
        z = .Slides(.Slides.Count).SlideNumber
        MsgBox z, vbDefaultButton1, "Total Slides"
    End With

    Dim myCol As Collection
    Set myCol = New Collection

    For i = 2 To z
        Set sld = ActivePresentation.Slides(i)
        For Each shp In sld.Shapes
            If x = 1 Then
            x = 1
            ElseIf shp.TextFrame.TextRange.Font.Color.RGB = RGB(255, 0, 0) Then
                myCol.Add CStr(i), CStr(i)
                x = 1
            End If
        Next shp
        x = 0
    Next

    Dim j As Long
    For j = 1 To myCol.Count
        Debug.Print myCol.Item(j)
    Next j

End Sub

1 个答案:

答案 0 :(得分:1)

并非所有形状都具有TextFrame,因此请在尝试访问它之前先进行检查

For i = 2 To z
    Set sld = ActivePresentation.Slides(i)
    For Each shp In sld.Shapes
        If shp.HasTextFrame Then
            If shp.TextFrame.TextRange.Font.Color.RGB = RGB(255, 0, 0) Then
                myCol.Add CStr(i), CStr(i)
                Exit For
            End If
        End If
    Next
Next

顺便说一句:您不需要x并在满足第一个条件时退出循环