VBA第四讲 循环语句

for循环

Sub ahole1()

Dim x As Integer

For x = 2 To 10 step 1

Range("d" & x) = Range("b" & x) * Range("c" & x)

Next x

End Sub

另外一种循环模式

Sub ahole3()

Dim rg As Range

For Each rg In Range("e2:e10")

rg = rg.Offset(0, -3) * rg.Offset(0, -2)

Next rg

End Sub

什么时候用for x = 2 to 10  step, 什么时候用for each rg in,取决于是否能找出数字规律,比如有断点的情况,这个时候就要用for each in

tips:给空白格赋值为0的代码

Sub ahole4()

Dim rg As Range

For Each rg In Range("a15:b20,d17:e20")

If rg = "" Then

rg = 0

End If

Next rg

End Sub

注意,先end if 在进入下一个rg循环,("a15:b20,d17:e20") 不规则区域表示法

查找断点代码




do循环

do循环容易造成死循环

Sub ahole5()

Dim x As Integer

x = 1

Do

x = x + 1

Range("f" & x) = Range("b" & x) * Range("b" & x)

Loop Until x = 9

End Sub

这段代码显示错误13,我并没有找到原因。正确代码如下

Sub ahole5()

Dim x As Integer

x = 1

Do

x = x + 1

Cells(x, 6) = Cells(x, 2) * Cells(x, 3)

Loop Until x = 9

End Sub

你可能感兴趣的:(VBA第四讲 循环语句)