'退出'不起作用

时间:2015-10-16 12:26:26

标签: excel vba excel-vba for-loop

在Excel VBA中执行反向循环,查找特定列中的最后一个填充单元格。一旦找到,它应该退出循环,但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

1 个答案:

答案 0 :(得分:5)

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

如果要查找列中最后填充的单元格,请使用以下内容:

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

无需循环。

也许是看Debugging VBA Code

的好时机