gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:15:55 25 4
gpt4 key购买 nike

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

最佳答案

Why does this code not work?? It throws compile error: 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

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

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

关于vba - 如何在 VBA 的 for 循环中添加 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com