For循环
For Each循环
用于遍历数据集中的所有元素,包括:数组
,对象集
。
语法:
For Each [元素变量] In [元素集合]
'循环执行的代码
Next [元素变量]
实例:循环打印所有工作表的名称
Sub printCode()
Dim ws As Worksheet
For Each ws In Worksheets
Debug.Print ws.Name
Next ws
End Sub
For Next循环
按指定次数,循环执行一段代码。
语法:
For [变量]=[初始值] To [结束值] Step [步长]
'循环执行的代码
Next
实例:计算1-10的累加值
Sub printCode()
Dim i As Integer
Dim sum As Integer
For i = 1 To 10 Step 1
sum = sum + i
Next
Debug.Print sum
End Sub
Exit For 语句:>用于跳出循环过程
Do While 循环
语法:
Do While [条件表达式]
'循环执行的代码
Loop
实例:计算1-10的累加值
点击查看代码
Sub printCode()
Dim i As Integer
Dim sum As Integer
i = 1
Do While i <= 10
sum = sum + i
i = i + 1
Loop
Debug.Print sum
End Sub
Do...Loop While 循环
语法:
Do
'循环执行的代码
Loop While [条件表达式]
标签:Do,VBA,Sub,sum,Next,While,循环 From: https://www.cnblogs.com/marshban/p/18277967Exit Do:用于跳出 Do While 循环。