如何在 VBA 的 do until 循环中指定范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18136341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:39:51  来源:igfitidea点击:

How do I specify a range in the do until loop in VBA?

vbaloops

提问by user2666018

I'm writing a code, so that

我正在写一个代码,所以

Do Until Range("A1:A10")=5 

""

Loop

I want a certain range to all have the same numbers, but VBA keeps on telling me there's a type mismatch. It seems that you can only work with one cell at a time or you would have to use the "And" function? (Do Until Range("A1")=5 And Range("A2")=5 , etc.) But is there a way to have the loop run until a certain range of cells satisfies the condition?

我希望某个范围内的所有数字都具有相同的数字,但 VBA 一直告诉我存在类型不匹配。似乎一次只能处理一个单元格,还是必须使用“与”功能?(做直到 Range("A1")=5 And Range("A2")=5 等)但是有没有办法让循环运行直到一定范围的单元格满足条件?

回答by tigeravatar

I think you're looking for something like this:

我想你正在寻找这样的东西:

Dim rngUpdate As Range

Set rngUpdate = Range("A1:A5")
Do Until WorksheetFunction.CountIf(rngUpdate, 5) = rngUpdate.Cells.Count
    'Your code goes here
Loop

回答by lowak

You can also use "for next", in your case:

在您的情况下,您还可以使用“for next”:

For i = 1 To 10
    If Cells(i, 1) = "5" Then
    Exit For ' when cell value is 5, it exits loop

    Else
    *do other code*
    End if

Next i