如何防止简单VBA代码溢出?

时间:2017-03-31 05:28:40

标签: vba

我是VBA的新手,正在编写一个简单的代码来获取A列中的所有数字,并在B列中为这些数字添加99.但是,一旦超过1000,就会发生溢出。我该怎么做才能切断while循环,这样它就不会溢出剩余的99列?谢谢!

Sub Button1_Click()

Dim n As Integer
n = 0
While Cells(1 + n, 1) <= 1000
    If Cells(1 + n, 2) = 0 Then
        Stop
    End If
    Cells(1 + n, 2).Value = Cells(1 + n, 1) + 99
    n = n + 1
Wend

End Sub

1 个答案:

答案 0 :(得分:0)

也许你在此之后:

Dim cell As Range

For Each cell In Range("A:A").SpecialCells(xlCellTypeConstants, xlNumbers) '<--| loop through column A cells with constant numeric content
    If cell.Value > 1000 Then Exit For '<--| exit loop as soon as the current cell value exceeds 1000
    cell.Offset(, 1).Value = cell.Value + 99
Next