【FOR...NEXT語句】
For counter = start To End [Step step]
[statements]
[Exit For]
[statements]
Next [counter]
【代碼區域】
計算1到1000的和
Private Sub qiuhe() Dim i As Integer '用於存儲列各項 Dim sum As Long '存儲結果項 Dim counter As Integer '循環計數 i = 1 sum = 0 counter = 1 For counter = 1 To 1000 sum = sum + i i = i + 1 Next MsgBox "1到1000各項求和為:" & sum, vbOKOnly, "結果" End Sub
【結果展示】
【Do...loop】
Do [{While | Until} condition]
[statements]
[Exit Do]
[Statements]
Loop
【代碼區域】
輸出循環體執行的次數
Private Sub 當循循環() Dim counter As Integer Dim condition As Boolean counter = 2 condition = True Do While condition = False counter = counter + 1 Loop MsgBox "循環體被執行了" & counter & "次", vbOKOnly, "測試當型循環" End Sub
【結果展示】
【while...Wend】
While condition
[statements]
Wend
【代碼區域】
Private Sub Wnd() Dim i As Integer Dim counter As Integer Dim sum As Long i = 1 sum = 0 counter = 1 While counter <= 1000 sum = sum + i i = i + 1 counter = counter + 1 Wend MsgBox "1到1000的和為:" & sum, vbOKOnly, "結果項" End Sub
【Tips】
while...wend循環執行的時候(1)判斷循環執行條件
(2)如果條件為True,則執行所有的statements,知道wend結束
(3)再返回while語句,再次檢測循環條件。知道條件為False時,才退出循環。
【結果展示】
【For Each...Next語句】
For Each element in group
[statements]
[exit for]
[statements]
next [element]
【代碼區域】
Private Sub 單元格區域賦值() Dim counter As Integer Worksheets("sheet2").Activate For Each yuanshu In Range("A2:A8") yuanshu.Value = counter counter = counter + 1 Next MsgBox "程序執行完畢,單元格已經被賦值", vbOKOnly, "為區域單元格賦值" End Sub
【展示結果】