【问题标题】:How to prevent overflow in simple VBA code?如何防止简单的 VBA 代码溢出?
【发布时间】:2017-08-25 06:36:59
【问题描述】:

我是 VBA 新手,正在编写一个简单的代码来获取 A 列中的所有数字并将 99 添加到 B 列中的这些数字。但是,一旦超过 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

【问题讨论】:

  • 你知道你的循环在到达Rows.Count之前永远不会结束吗?使用您的编码方式,一个空单元格将返回零,因此它会继续运行。 Stop 并不意味着退出循环。它仅模拟断点。仅供参考:Break out of a While…Wend loop in VBA

标签: vba


【解决方案1】:

也许你在追求这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多