如何做循环检查,求和单元格值并停在正确的位置



我想在求和值后停止循环​​在该列中超过40R〃;D1:D10〃;{10,12,123,2321,12,…}并写下需要添加的数字/单元格数。我需要使用循环

Sub LOOOP ()
Dim sum As Integer
Dim i As Integer
sum = 0
Do
For i = 1 To 10
sum = sum + Cells(i, 4).Value
Next i
Loop While sum < 40
End Sub

这个程序应该可以解决您的问题:

Sub LOOOP()
Dim sum As Integer
Dim sumTmp As Integer
Dim i As Integer
Dim countIteration As Integer
sum = 0
countIteration = 0
For i = 1 To 11
countIteration = countIteration + 1
sum = sum + Cells(i, 4).Value
If (sum > 40) Then
Exit Do
End If
Next i
If (sum > 40) Then
Cells(1, 5).Value = "Sum: " + Str(sum)
Cells(1, 6).Value = "Iterations: " + Str(countIteration)
Else
sum = 20
Cells(1, 5).Value = "Sum: " + Str(sum)
End If
End Sub

相关内容

最新更新