分支结构
IF分支
If < expression > Then
< other code goes here >
End If
SELECT CASE分支
Select Case < expression >
Case <possibility 1>
< code goes here >
Case <possibility 2>
< other code goes here >
Case <possibility 3>
< other code goes here >
Case <possibility n>
< other code goes here >
Case Else
< other code goes here >
End Select
循环结构
FOR NEXT 知道准确的循环次数
Option Explicit
Dim lngIndex
For lngIndex = 10 To 14
MsgBox "Loop Index: " & lngIndex
Next
Option Explicit
Dim lngIndex
For lngIndex = 10 To 18 Step 2
MsgBox "Loop Index: " & lngIndex
Next
Option Explicit
Dim lngIndex
For lngIndex = 5 To 1 Step –1
MsgBox "Loop Index: " & lngIndex
Next
Option Explicit
Dim lngIndex
For lngIndex = –10 To –1
MsgBox "Loop Index: " & lngIndex
Next
Option Explicit
Dim lngIndex
For lngIndex = –10 To –20 Step –2
MsgBox "Loop Index: " & lngIndex
Next
Option Explicit
Dim lngOuter
Dim lngInner
For lngOuter = 1 to 5
MsgBox "Outer loop index: " & lngOuter
For lngInner = 10 to 18 Step 2
MsgBox "Inner loop index: " & lngInner
Next
Next
For Each…Next
For Each…Next 最常见的是用于遍历集合,但它还
可以用于遍历数组中的元素。无论数组中有多少元素,也无论它有多少维度,For Each…Next 循环都能遍历其中的每个元素。可以用 Exit For 语句随时终止循环。
Option Explicit
Dim astrColors(3)
Dim strElement
astrColors(0) = "Red"
astrColors(1) = "Green"
astrColors(2) = "Blue"
astrColors(3) = "Yellow"
For Each strElement In astrColors
MsgBox strElement
Next
DO LOOP
Do ...Loop While
Do While ...Loop
Do ...Loop Until
Do Until ...Loop
Do 循环是最通用的循环结构。因为您可以非常方便地用它根据任何您所需的标准来设定循环次数。
Do 循环的威力来自于 While 和 Until 关键字。While 和 Until 既可以用在循环的开始,也可以用在循环的结尾来控制是否要再次执行循环。
至少执行一次代码。
可以用 ExitDo 随时跳出 Do 循环。
Option Explicit
Dim boolLoopAgain
Dim lngLoopCount
Dim strResponse
boolLoopAgain = False
lngLoopCount = 0
Do
boolLoopAgain = False
lngLoopCount = lngLoopCount + 1
strResponse = InputBox("What is the magic word?")
If UCase(Trim(strResponse)) = "PLEASE" Then
MsgBox "Correct! Congratulations!"
Else
If lngLoopCount < 5 Then
MsgBox "Sorry, try again."
boolLoopAgain = True
Else
MsgBox "Okay, the word we wanted was "Please"."
End If
End If
Loop While boolLoopAgain
Option Explicit
Dim boolLoopAgain
Dim lngLoopCount
Dim strResponse
boolLoopAgain = True
lngLoopCount = 0
Do While boolLoopAgain
boolLoopAgain = False
lngLoopCount = lngLoopCount + 1
strResponse = InputBox("What is the magic word?")
If UCase(Trim(strResponse)) = "PLEASE" Then
MsgBox "Correct! Congratulations!"
Else
If lngLoopCount < 5 Then
MsgBox "Sorry, try again."
boolLoopAgain = True
Else
MsgBox "Okay, the word we wanted was 'Please'."
End If
End If
Loop
While…Wend
Option Explicit
Dim lngCounter
lngCounter = 0
While lngCounter <= 20
lngCounter = lngCounter + 1
'< other code goes here >
Wend