If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped.
Syntax of the If...Then selection
If
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If
If...Then...Else
If condition1 Then
statements1
Else
statements2
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then
txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If
Select Case
Can be used as an alternative to the If...Then...Else structure, especially when many comparisons are involved.
Select Case ShirtSize
Case 1
SizeName.Caption = "Small"
Case 2
SizeName.Caption = "Medium"
Case 3
SizeName.Caption = "Large"
Case 4
SizeName.Caption = "Extra Large"
Case Else
SizeName.Caption = "Unknown size"
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
Do...Loop
Do While condition
statements
Loop
First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.
For...Next
For counter = start To end
statements
Next
- The counter is set to the value of start.
- Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed.
- At Next, counter is incremented and goes back to step 2).
More will be covered on Control strucures as it becomes necessary in upcoming lessons. Meanwhile,if you want to know more, consult the VB Language Reference.
0 comments:
Posting Komentar