简体   繁体   中英

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

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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