vba 如何在VBA的for循环中添加if语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41962792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:43:08  来源:igfitidea点击:

How to add an if statement inside a for loop in VBA?

vbafor-loopnext

提问by pnkjmndhl

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 

Why does this code not work?? It throws compile error: Next without for

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

回答by David Zemens

Why does this code not work?? It throws compile error: Next without for

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

Because you have a nextwithout a corresponding For. For/Nextand For Each/Nextmust be paired, you can't open a Forloop without a Nextand you can't use Nextwithout `For.

因为你有一个next没有相应的For. For/Next并且For Each/Next必须配对,没有a就不能打开For循环NextNext没有`for就不能使用。

Simply:

简单地:

if a = dumm then a = a + 1

This increments your avalue within the loop. I'm unclear as to why you think this isn't applicable, because whether you increment aand thenrun the code, or skip to the next a(which is functionally equivalent to incrementing it via +1), the result should be same

这会增加您a在循环中的价值。我不清楚为什么你认为这是不适用的,因为无论你增加a然后运行该代码,或跳到下a(这是功能上等同于通过增加它+1),结果应该是相同的

Or, you could add a label and a GoTostatement:

或者,您可以添加标签和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 

Or, and my preference, just use proper boolean expressions:

或者,根据我的喜好,只需使用适当的布尔表达式:

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

If you don't want to continue the loop at all, then either add an Exitstatement,

如果您根本不想继续循环,则添加一条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

or use a Do/Whileloop with proper escape conditions:

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

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