【问题标题】:'Exit For' is not working“退出”不起作用
【发布时间】:2015-10-16 12:26:25
【问题描述】:

在 Excel VBA 中执行反向 for 循环,查找特定列中最后填充的单元格。一旦找到,它应该退出循环,但 Exit For 不起作用,并继续循环返回。有什么想法吗?

    rewind:
'            so we 're still "under", rollback to the right line
            While Not Range("I" & a).Value = getsum
                a = a - 1
                On Error GoTo TryCatch
                If Not Range("E" & a).Value = "" Then
                    Rows(a).Select
                    currfield = Range("E" & a).Value
                    runningstrsum = runningstrsum - currentstrsum 'we're switching streets
'                    and since we just lost currentstrsum, we have to reset it to the last one, yay
                    For c = a - 1 To 2 Step -1
                        If Not Range("E" & c).Value = "" Then 'there it is
                            currentstrsum = Range("E" & c).Value
                            Exit For
                        End If
                    Next c
                End If
            Wend
            If overunder < 0 Then 'go back to overunder<
                GoTo goodjobunder
            ElseIf overunder = 0 Then
                GoTo goodjobeven
            End If

【问题讨论】:

    标签: vba excel for-loop


    【解决方案1】:

    您只是退出了内部循环,代码将在此循环之外恢复 - 它仍在 While 循环内,因此重新进入 For 循环。

    如果您想查找列中最后一个填充的单元格,只需使用以下内容:

    Dim lastCell As Excel.Range
    Set lastCell = Range("E" & Rows.Count).End(xlUp)
    

    无需循环。

    也许也是看看Debugging VBA Code的好时机

    【讨论】:

    • 很好的答案,无需循环查找最后一个单元格。作为旁注,您可以通过设置“标志”来退出多个循环,以告诉进程何时退出另一个循环。在这里搜索应该会产生多个结果。
    • 您也可以使用带有标签的GoTo 语句 - 但如果使用不当,这可能会比循环造成更多混乱:)
    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多