简体   繁体   English

VBA:While循环不适用于多个(或)条件

[英]VBA : While loop not working with multiple (or) condtions

Sub Demo()

Dim x As Integer
Dim y As Integer

x = 20
y = 15

While ((x <> 10) Or (y <> 10))
    x = x - 1
    y = y - 1
    Debug.Print x & " : " & y
    Wend

Debug.Print x & " : " & y
End Sub

This loop goes in infinte mode, instead of breaking at conditions, when x or y become equal to 10. I tried using Do..While..Loop , but even that doesn't work. 当x或y等于10时,此循环进入无限模式,而不是在条件下中断。我尝试使用Do..While..Loop ,但即使这样也不起作用。 Can't we use multiple condtions with While statement. 我们不能While语句中使用多个条件。

Replace or with and ! and替换or

Even if x is 10, y is not equal 10 and vice versa, therefore your condition is always true and your loop will go on forever... 即使x为10,y也不等于10,反之亦然,因此您的条件始终为true,并且循环将永远持续下去...

You just need to change the logic used from "OR" to "AND". 您只需要将使用的逻辑从“或”更改为“与”。

Everytime it iterates currently, it's checking either of the things are true, however, if y = 10, and X does not, you will continue looping as it evaluates both. 当前每次迭代时,它都会检查其中的任何一个是否成立,但是,如果y = 10,而X则不成立,那么您将继续循环进行评估。

With "AND", as soon as one condition is met your loop breaks. 使用“ AND”,只要满足一个条件,循环就会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM