2015-10-16 80 views
0

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

回答

5

你只是退出内部循环,代码将恢复超出这个循环 - 这仍然是While循环中,因此重新进入For循环。

如果你想找到的最后一个单元格填充一列中只使用类似:

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

无需循环。

也可能是一个好时机,看看Debugging VBA Code

+1

伟大的答案,无需环路找到最后一个单元格。作为附注,您可以通过设置“标志”来告诉进程何时退出其他循环,从而退出多个循环。在这里搜索应该会产生多个结果。 – Kyle

+1

你也可以使用带有标签的'GoTo'语句 - 但如果没有正确使用,会导致比循环更多的困惑:) –