【问题标题】:How to add an if statement inside a for loop in VBA?如何在 VBA 的 for 循环中添加 if 语句?
【发布时间】:2017-06-17 04:44:07
【问题描述】:
For a = 1 to 10
    if a = dumm then next a 'this statement should avoid running the subsequent codes if the if statement is true (similar to continue in c++
    end if
    'statements that need to run when the if statement is not true

next a 

为什么这段代码不起作用?它抛出编译错误:Next without for

【问题讨论】:

  • 去掉next a,if语句中需要有动作
  • if a = dumm then a = a + 1
  • if a = dumm then goto... (这需要添加一个可以与goto 语句一起使用的标签。
  • @mo.h 如果没有下一个 a 循环不会运行 10 次
  • @DavidZemens 运行剩余的代码。我不想那样。

标签: vba for-loop next


【解决方案1】:

为什么这段代码不起作用?它抛出编译错误:Next without for

因为您有一个next,但没有对应的ForFor/NextFor Each/Next 必须配对,没有Next 就不能打开For 循环,没有`For 也不能使用Next

简单地说:

if a = dumm then a = a + 1

这会增加循环中的 a 值。我不清楚你为什么认为这不适用,因为无论你增加 athen 运行代码,还是跳到下一个 a (这在功能上相当于增加通过+1),结果应该是一样的

或者,您可以添加标签和GoTo 语句:

For a = 1 to 10
    if a = dumm then 
        GoTo MyLabel 
    end if
    'statements that need to run when the if statement is not true

MyLabel:
next a 

或者,根据我的偏好,只使用正确的布尔表达式:

For a = 1 to 10
    if not a = dumm Then
        'statements that need to run when the if statement is not true
    end if
Next

如果您根本不想继续循环,则添加Exit 语句,

For a = 1 to 10
    if a = dumm Then Exit For
    'statements that need to run when the if statement is not true

Next

或使用带有适当转义条件的Do/While 循环:

a = 1
Do 
    'statements go here...    
    a = a + 1
Loop While a <= 10 and Not a = dumm 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多