【VBA编程】07.循环结构语句

【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

 

【展示结果】

 

posted @ 2016-12-21 11:59  OLIVER_QIN  阅读(2333)  评论(0编辑  收藏  举报