如何在 VBA 的 for 循环中添加 if 语句?
How to add an if statement inside a for loop in VBA?
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
为什么这段代码不起作用??它抛出 编译错误:下一个没有 for
Why does this code not work?? It throws compile error: Next without for
因为你有一个 next
而没有相应的 For
。 For/Next
和 For Each/Next
必须配对,没有 Next
就不能打开 For
循环,没有 `For.[ 就不能使用 Next
。 =30=]
简单地说:
if a = dumm then a = a + 1
这会增加循环内的 a
值。我不清楚为什么你认为这不适用,因为无论你是递增 a
and then 运行 代码,还是跳到下一个 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
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
为什么这段代码不起作用??它抛出 编译错误:下一个没有 for
Why does this code not work?? It throws compile error: Next without for
因为你有一个 next
而没有相应的 For
。 For/Next
和 For Each/Next
必须配对,没有 Next
就不能打开 For
循环,没有 `For.[ 就不能使用 Next
。 =30=]
简单地说:
if a = dumm then a = a + 1
这会增加循环内的 a
值。我不清楚为什么你认为这不适用,因为无论你是递增 a
and then 运行 代码,还是跳到下一个 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