for next 语句中的“整数超出范围”错误

Posted

技术标签:

【中文标题】for next 语句中的“整数超出范围”错误【英文标题】:"integer out of range" error in a for next statement 【发布时间】:2014-05-08 15:42:16 【问题描述】:

我对此已经发疯了,我确信错误就在我面前,我只是看不到它。感谢调试以下语句的所有帮助。

我在一个 ppt 演示文稿中有多张幻灯片。在一些幻灯片中,有一个星形和一个带有文本“Hold”或“Yearly”的文本框。仅当没有带有“Hold”或“Yearly”的文本框时,我才想更改星星的颜色。

Sub Set_Star_Shape_Color_Green_Test()
    Dim PPApp As Object ' As PowerPoint.Application
    Dim PPPres As Object ' As PowerPoint.Presentation
    Dim PPSlide As Object ' As PowerPoint.Slide
    Dim iShpCnt1 As Integer
    Dim iShpCnt2 As Integer
    Dim iShpCnt3 As Integer
    Dim iSlideCnt As Integer
    Dim iBoxTopPos As Integer
    Dim sHold As String
    Dim sStar As String
    Dim sTbox As String
    Dim sTColor As String
    Dim oShp As Shape

    Set PPApp = GetObject(, "Powerpoint.Application")
    Set PPPres = PPApp.ActivePresentation
    Set PPSlide = PPPres.Slides _
        (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)

    iShpCnt0 = PPSlide.Shapes.Count
    For iShpCnt1 = 1 To iShpCnt0    'PPSlide.Shapes.Count
        iBoxTopPos = 260
        ' iSlideCnt = 2 removed
        sHold = ""
        sStar = ""

        iShpCnt1 = 1
        For iShpCnt1 = 1 To PPSlide.Shapes.Count
            If iShpCnt1 <= PPSlide.Shapes.Count Then
                **Set oSh = PPApp.ActivePresentation.Slides(iSlideCnt).Shapes(iShpCnt1)  ' this is where i am getting the integer out of range error**
                If oSh.Name.Text Like "*Hold*" Or oSh.Name.Text Like "*Yearly*" Then
                    sHold = oSh.Name
                End If
                If oSh.Name Like "*Star*" Then
                    sStar = oSh.Name
                End If
            End If

        Next

        For iShpCnt2 = 1 To iShpCnt0 ' this fixed the error
            Set oSh = PPApp.ActivePresentation.Slides(iSlideCnt).Shapes(iShpCnt2)
            If oSh.Name Like "*Star*" And sHold = "" Then
                oSh.Fill.ForeColor.RGB = RGB(50, 205, 50) ' change the color to green
            End If
        Next

        ' go to next slide
        If PPSlide.SlideIndex + 1 < PPPres.Slides.Count Then
            PPApp.ActiveWindow.View.GotoSlide PPSlide.SlideIndex + 1
            Set PPSlide = PPPres.Slides _
                (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex + 1)
        End If

    Next

    ' Clean up
    Set PPSlide = Nothing
    Set PPPres = Nothing
    Set PPApp = Nothing

End Sub

【问题讨论】:

【参考方案1】:

您将迭代器设置为两个。

For iSlideCnt = 1 To PPPres.Slides.Count
    iBoxTopPos = 260
    iSlideCnt = 2 <--- right here

如果您只有一张幻灯片,它将超出范围。

【讨论】:

感谢您的回复。我的 ppt 中有多张幻灯片,所以它仍然应该可以工作。无论如何,我删除了该语句(iSlideCnt = 2 只是想让其他人知道我已通过将“For iShpCnt1 = 1 To PPSlide.Shapes.Count”更改为“For iShpCnt1 = 1 To iShpCnt0”修复了错误

以上是关于for next 语句中的“整数超出范围”错误的主要内容,如果未能解决你的问题,请参考以下文章

python字符类型

打印来自 For Each 函数 VBA 的数组结果得到下标超出范围错误

VBS_For Each...Next

在VB中 for 循环嵌套语句的用法语解释(必须清楚!!)

c++和opencv中的向量下标超出范围错误

VB 的 with 语句中语句能嵌套循环语句吗?比如for next