【问题标题】:Error with Nested loops in Excel VBAExcel VBA 中的嵌套循环出错
【发布时间】:2017-11-21 05:44:24
【问题描述】:

我在 Excel VBA 上的代码有问题。我正在尝试编写一个嵌套循环。但我不断收到编译错误: Next without For ( the line with Next r)

这是我的代码

Sub clear()
r = 2
i = 310

For c = 15 To 28

r = 2
i = 310

For r = 2 To 306

If Cells(r, c) > Cells(306, c) Then
If Cells(r, 4) <> Cells(i - 1, c) Then
[ Cells(i, c) = Cells(r, 4) i = i + 1]


r = r + 1
Next r

Cells(308, c) = i - 309

Next c

End Sub

提前致谢

【问题讨论】:

  • 尝试缩进你的代码,你可能会发现你有 2 x Ifs 没有End If,这可能是原因。此外,在您共享的代码中,您没有对变量 I 执行任何操作,您可以将 I 替换为 310(或在顶部声明为 Const)
  • 感谢@ShaiRado,我添加了 End if 并且它有效

标签: excel for-loop compiler-errors nested vba


【解决方案1】:

您(至少)缺少endifs。 请检查下面发布的代码是否符合您的预期任务。

加号:

  1. require explicit declaration of variables 总是很方便。

  2. 不单独使用Cells总是很方便的,见this answer。

  3. r = r + 1 行很奇怪。 r 已经通过循环递增。

建议的修改代码(我手头没有测试它的系统)。

Option Explicit

Sub clear()
    Dim r as Integer, i as Integer, c as Integer
    Dim ws As Worksheet
    Set ws = ActiveSheet   ' or whatever you want
    'r = 2
    i = 310
    For c = 15 To 28
        'r = 2
        'i = 310
        For r = 2 To 306
            If ( ws.Cells(r, c) > ws.Cells(306, c) ) Then
                If ( ws.Cells(r, 4) <> ws.Cells(i - 1, c) ) Then
                    [ ws.Cells(i, c) = ws.Cells(r, 4) i = i + 1]   ' check syntax
                endif
            endif
            r = r + 1    ' check this
        Next r
        ws.Cells(308, c) = i - 309
    Next c
End Sub

【讨论】:

  • 你有一个 For r = 2 To 306 循环,在让它增加 Next r 之前,你要保持另一个 r = r + 1 ?
  • @ShaiRado - 当然,我在评论那条奇怪的线。即使在极少数情况下,人们可能想要这样做,但我不认为这是一种这样的情况。
  • @sancho.s 如何将焦点更改为不同的工作表。我写了一个代码,我想为表 3 运行它,但代码正在为表 2 运行。
  • @FranklinVarghese - set ws = Worksheets("sheet 3") 或类似的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多