VB For 循环语句的用法
1、For循环的格式:
For 循环变量 = 初值 To 终值 [Step 步长]
[循环体]
Next [循环变量]
注意:
1) 当步长 > 0 时
循环执行的条件:循环变量 <= 终值
2) 当步长 < 0 时
循环执行的条件:循环变量 >= 终值
强行退出 For 循环,请使用 Exit For。
1、举例1: 单击命令按钮 Command1 后,先后弹出很多消息框,消息内容一开始是 1,最后是 100,每弹出一次,消息内容加 1,也就是 1; 2; 3; ...; 98; 99; 100。
VB 代码如下:
Private Sub Command1_Click()
Dim i As Long
For i = 1 To 100
MsgBox i
Next
End Sub
2、举例2: 单击命令按钮 Command1 后,弹出消息框,消息内容为: 100 以内所有数的平方和。
VB 代码如下:
Private Sub Command1_Click()
Dim i As Long, Sum As Long
For i = 1 To 100
Sum = Sum + i ^ 2
Next
MsgBox Sum
End Sub
1、如果没有 For 语句,那么我们应该如何实现循环呢?
2、如果使用 For 语句,代码如下:
Private Sub Form_Load()
For i = 1 To 100
MsgBox i, vbInformation
Next
MsgBox "Finished", vbCritical
End Sub
3、如果不用 For 语句,我们可以这样做:
Private Sub Form_Load()
Dim i As Long
i = 1
While i <= 100 '使用 While 语句
MsgBox i, vbInformation
i = i + 1 '这句话千万不能少!否则会造成死循环!!
Wend
MsgBox "Finished", vbCritical
End Sub
4、如果连 While 都不能用,我们还可以这样做:
Private Sub Form_Load()
Dim i As Long
i = 1
Do While i <= 100 '使用 Do While 语句
MsgBox i, vbInformation
i = i + 1 '这句话千万不能少!否则会造成死循环!!
Loop
MsgBox "Finished", vbCritical
End Sub
5、如果连 Do While 都不能用,我们还可以这样做:
Private Sub Form_Load()
Dim i As Long
i = 1
Do Until i > 100 '使用 Do Until 语句
MsgBox i, vbInformation
i = i + 1 '这句话千万不能少!否则会造成死循环!!
Loop
MsgBox "Finished", vbCritical
End Sub
6、如果连 Do Until 都不能用,我们就只能用递归的方法了:
Dim i As Long
Private Sub Form_Load()
Repeat i, 1, 100
MsgBox "Finished", vbCritical
End Sub
Private Sub Repeat(VarName, ByVal InitialValue As Long, ByVal StopValue As Long, Optional ByVal Step As Long = 1)
'参数 说明
'
'VarName 相当于 For 语句中的“循环变量”。
'InitialValue 相当于 For 语句中的“初值”。
'StopValue 相当于 For 语句中的“终值”。
'Step 相当于 For 语句中的“步长”。
VarName = InitialValue
RepeatStatement VarName, InitialValue, StopValue, Step
End Sub
Private Sub RepeatStatement(VarName As Long, ByVal InitialValue As Long, ByVal StopValue As Long, ByVal Step As Long)
Select Case Step
Case Is < 0
If StopValue > InitialValue Then Exit Sub
Case Is > 0
If StopValue < InitialValue Then Exit Sub
End Select
'要循环的语句 (开始)
MsgBox VarName, vbInformation
'要循环的语句 (结束)
VarName = VarName + Step
RepeatStatement VarName, VarName, StopValue, Step '调用自身过程,从而实现循环的目的
End Sub
你看看,是不是很麻烦?Microsoft 可不是白搞 For, While, Do While, Do Until 等语句的!