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

pnk*_*dhl 1 vba for-loop next

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 
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*ens 6

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

因为你有一个next没有相应的For. For/Next并且For Each/Next必须配对,你不能在没有a的For情况下打开一个循环而Next你不能Next没有`For.

只是:

if a = dumm then a = a + 1
Run Code Online (Sandbox Code Playgroud)

这会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 
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

如果你根本不想继续循环,那么要么添加一个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
Run Code Online (Sandbox Code Playgroud)

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

a = 1
Do 
    'statements go here...    
    a = a + 1
Loop While a <= 10 and Not a = dumm 
Run Code Online (Sandbox Code Playgroud)