为什么这个程序,应该总结每列,停止后只有一列?

这个程序创build一个数字表,然后尝试总结,逐行。 我使用IsBlank()来testing最上面的单元格是否为空。 如果它是空白的,它应该结束循环,但如果没有,循环应该继续。 但是,在第一次循环之后它会一直保持结束状态。 这是为什么?

我有一种感觉,这真的很明显。

编辑:我应该注意,整个“反”的东西是在那里,因为我打算开始玩,如果这个工作。 它没有工作,所以我在这里!

 Option Explicit Dim Counter As Long Dim i As Long Dim col As Long Dim row As Long Sub SumRange() For col = 1 To 8 For row = 1 To 6 Cells(row, col) = Rnd Next row Next col Counter = 6 For i = 1 To 9 If IsEmpty(Cells(1, i)) = False Then Cells(Counter + 1, i) = Application.WorksheetFunction.Sum(Range(Cells(1, i), Cells(Counter, i))) Else End If End Next MsgBox Cells(4, 5) End Sub 

有两个问题:

  1. End语句是不正确的。 如果我没有记错, End意味着结束程序 。 你必须明确地陈述你的结局( End IfEnd With ,…)。 在这种情况下你的意思是End If

  2. 您需要使用Exit For跳出for循环。 我认为你的意思是你现在的End If结论是这样的。

我不知道你在做什么,但是你也可以考虑使用While Not IsEmpty(Cells(1, i))的条件来使用while循环,然后在循环内增加计数器i 。 对我来说,这感觉比一个有跳跃的循环好一点。

从代码中删除ElseEnd (仅包含这些语句的行),循环执行九次。

End语句指示VBA …结束您的代码。 所以它只是退出。

我强烈build议重构你的代码,它可以变得更有效率:

 Sub SumRange() Dim values(1 To 6, 1 To 8) As Double Dim i As Long, j As Long ' populate array For i = LBound(values) To UBound(values) For j = LBound(values, 2) To UBound(values, 2) values(i, j) = Rnd Next j Next i ' blast array onto worksheet in one go Range("A1").Resize(UBound(values), UBound(values, 2)).value = values ' add sum formulas in one go Range("A1").Resize(, UBound(values, 2)).Offset(UBound(values)).FormulaR1C1 = _ "=SUM(R[-" & UBound(values) & "]C[0]:R[-1]C[0])" MsgBox Cells(4, 5) End Sub