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

时间:2017-01-31 16:40:34

标签: vba for-loop next

.img-2 {
display: inline;
width: 20%;
height: 20%;
margin-top: -25%;
}

为什么这段代码不起作用?它抛出编译错误:下一步没有

1 个答案:

答案 0 :(得分:5)

  

为什么这段代码不起作用?它抛出编译错误:下一步没有

因为您的next没有相应的ForFor/NextFor Each/Next必须配对,如果没有For,则无法打开Next循环,如果没有“For”,则无法使用Next。 / p>

简单地:

if a = dumm then a = a + 1

这会增加循环中的a值。我不清楚为什么你认为这不适用,因为你是否增加a然后运行代码,或者跳到下一个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 
相关问题