卡饭网 > 其他 > 正文

vba do loop的几个例子

来源:本站整理 作者:梦在深巷 时间:2013-03-26 16:02:56

一、Do…Loop语句的语法

Do[While I Until<逻辑表达式>]

<循环体>

Loop[While I Until<逻辑表达式>]

当逻辑表达式的值为True时,使用While关键字执行循环体,直到逻辑表达式的值为False时跳出循环体,即执行Do While-Loop循环语句。

当逻辑表达式的值为False时,使用Until关键字执行循环体,直到逻辑表达式的值为True时跳出循环体,即执行Do Until-Loop循环语句。

在大多数情况下Do while.Loop循环语句与Do Until—Loop循环语句可以互换使用,只需将循环条件取反即可。但对于需要先判断再执行的一些操作,最好使用Do While-Loop循环语句。

另外,使用Do-Loop循环语句时,需要在循环体内使用“Exit Do”语句跳出Do-Loop循环,进而执行Loop后面的一条语句。

二、do…loop的几个例子

①例子

Dim myCnt As Long

myCnt = 1

Do While myCnt <= 5

Cells(myCnt, 3).Value = Cells(myCnt, 1).Value * Cells(myCnt, 2).Value

myCnt = myCnt + 1

Loop

当myCnt小于等于5时循环,否则就退出循环。

②例子

Dim myCnt As Long

myCnt = 1

Do

Cells(myCnt, 3).Value = Cells(myCnt, 1).Value * Cells(myCnt, 2).Value

myCnt = myCnt + 1

Loop While myCnt<=5

③例子

Dim myCnt As Long

myCnt = 1

Do

Cells(myCnt, 3).Value = Cells(myCnt, 1).Value * Cells(myCnt, 2).Value

myCnt = myCnt + 1

If myCnt>5 Then Exit Do

Loop

④例子

counter = 0

myNum = 9

Do Until myNum = 10

myNum = myNum - 1

counter = counter + 1

If myNum < 10 Then Exit Do

Loop

MsgBox "The loop made " & counter & " repetitions."

相关推荐