【问题标题】:For loop being skipped without any cause in VBA在VBA中无任何原因跳过for循环
【发布时间】:2017-05-03 06:50:41
【问题描述】:

问题:For currentRow = 25 To rowCount 之后,for 语句的其余部分不断被无缘无故地跳过。

我在这个有问题的代码块之前还有另外两个 For 语句,它们的格式与这个相同,并且都可以正常工作。

Public Sub WeightB()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 7
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    For currentRow = 24 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Exit For
        End If
    Next
End Sub

我已经推荐了For loops being skipped without cause in VBA,但仍然无法解决这个问题。

【问题讨论】:

  • rowCountFor 循环之前的值是多少?
  • 我试过 MsgBox rowCount 显示 22。
  • @Peh 但是为什么前两个语句有效?这对我来说很奇怪。非常感谢您的建议!

标签: vba excel


【解决方案1】:

如果 rowCount,根据您的澄清评论,是 22,那么您的 For 循环变为

For currentRow = 24 To 22

这显然是一个空操作,因为 24 不可能数到 22。如果您需要在最终数字的 方向 上计数,那么您可以使用类似的东西

For currentRow = 24 To rowCount Step Iif(rowCount - 24 < 0, -1, +1)

但这真的是你想要做的吗?此外,开始使用 Long 类型作为行号和列号,现在工作表有超过 32767 行,并在所有模块的顶部使用 Option Explicit 来避免烦人的自发变量创建。

【讨论】:

  • 值得一提,如果这是故意的,但您想从 24 变为 22 (24,23,22),那么 OP 应该使用 For currentRow = 22 To 24 Step -1
  • 我可能回答错了。我想要做的是从 D24 输入数据到 D42。但我希望这个脚本找到该范围内的空单元格以输入输入。
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
相关资源
最近更新 更多