Using Conditional Statements
- If…Then…Else statement
- Select Case statement
Making Decisions Using If…Then…Else
The If…Then…Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. For information about comparison operators, see Comparison Operators.
If…Then…Else statements can be nested to as many levels as you need.
Running Statements if a Condition is True
Sub FixDate() Dim myDate myDate = #2/13/95# If myDate < Now Then myDate = Now End Sub
Sub AlertUser(value) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True End If End Sub
Running Certain Statements if a Condition is True and Running Others if a Condition is False
Sub AlertUser(value) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True Else AlertLabel.Forecolor = vbBlack AlertLabel.Font.Bold = False AlertLabel.Font.Italic = False End If End Sub
Deciding Between Several Alternatives
Sub ReportValue(value) If value = 0 Then MsgBox value ElseIf value = 1 Then MsgBox value ElseIf value = 2 then Msgbox value Else Msgbox "Value out of range!" End If End Sub
You can add as many ElseIf clauses as you need to provide alternative choices, but extensive use of the ElseIf clauses often becomes cumbersome. A better way to choose between several alternatives is the Select Case statement.
Making Decisions with Select Case
The Select Case structure provides an alternative to If…Then…ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If…Then…Else statement, but it makes code more efficient and readable.
Select Case Document.Form1.CardType.Options(SelectedIndex).Text Case "MasterCard" DisplayMCLogo ValidateMCAccount Case "Visa" DisplayVisaLogo ValidateVisaAccount Case "American Express" DisplayAMEXCOLogo ValidateAMEXCOAccount Case Else DisplayUnknownImage PromptAgain End Select
Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If…Then…ElseIf structure can evaluate a different expression for each ElseIf statement. You can replace an If…Then…ElseIf structure with a Select Case structure only if each ElseIf statement evaluates the same expression.