VBA–循环语句
1.Do Loop
(1)Do while
Sub t1()
x = 1
Do While x < 18
x = x + 1
Cells(x, 4) = Cells(x, 2) * Cells(x, 3)
Loop
End Sub
(2)Do until
Sub t2()
Dim x As Integer
x = 1
Do
x = x + 1
Cells(x, 4) = Cells(x, 2) * Cells(x, 3)
Loop Until x = 18
End Sub
2.For Next
Sub t3()
Dim x As Integer
For x = 2 To 100 Step 2
Range(“d” & x) = Range(“b” & x) * Range(“c” & x)
Next x
End Sub
3.For each in Next
Sub t4()
Dim rg As Range
For Each rg In Range(“D2”,Range(“D2”).End(xlDown))
rg = rg.Offset(0, -1) * rg.Offset(0, -2)
Next rg
End Sub
循环语句 | 条件 |
---|---|
Do Loop | 符合条件循环或直到符合条件结束循环,没有循环次数 |
For Next | 指定起止数值范围循环,有循环次数 |
For Each in Next | 针对对象集合或是数组循环,循环次数由对象集合元素个数决定 |