【Excel VBA】Do...until / Do...while loop

【Excel VBA】Do...until / Do...while loop_第1张图片
Do Until/while适用于不知道要loop多少次的情况

1. Do until

Sub Simple_Do_Until_V1()
    StartCell = 8
    Do Until Range("A" & StartCell).Value = ""
        Range("B" & StartCell).Value = Range("A" & StartCell).Value + 10
        StartCell = StartCell + 1
    Loop
End Sub

另一种写法,不同的Do until条件

Sub Simple_Do_Until_V2()
    StartCell = 8
    Do Until StartCell = 14
        Range("B" & StartCell).Value = Range("A" & StartCell).Value + 10
        StartCell = StartCell + 1
    Loop

End Sub

效果都是一样的=》
【Excel VBA】Do...until / Do...while loop_第2张图片

2. Do while

同一个效果的Do while写法

Sub Simple_Do_While()
    StartCell = 8
    Do While Range("A" & StartCell).Value <> ""
        Range("C" & StartCell).Value = Range("A" & StartCell).Value + 10
        StartCell = StartCell + 1
    Loop

End Sub

3. Do Exit

Sub Simple_Do_Until_Conditional()
    StartCell = 8
    Do Until StartCell = 14
        ' 如果Quantity列为0,则退出loop
        If Range("A" & StartCell).Value = 0 Then Exit Do
        Range("D" & StartCell).Value = Range("A" & StartCell).Value + 10
        StartCell = StartCell + 1
    Loop
End Sub

【Excel VBA】Do...until / Do...while loop_第3张图片

你可能感兴趣的:(VBA)