Home

Introduction to Conditional Statements

 

Checking Whether a Condition is True/False

 

Introduction

In some programming assignments, you must find out whether a given situation bears a valid value. This is done by checking a condition. To support this, the Visual Basic language provides a series of keywords and operators that can be combined to perform this checking. Checking a condition usually produces a True or a False result.

Once the condition has been checked, you can use the result (as True or False) to take action. Because there are different ways to check a condition, there are also different types of keywords to check different things. To use them, you must be aware of what each does or cannot do so you would select the right one.

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start Microsoft Excel
  2. On the Ribbon, click Developer and, in the Code section, click Visual Basic
  3. On the main menu, click Insert -> UserForm
  4. Design the form as follows:
     
    Form Design: Employee Information
    Control Name Caption
    Label First Name:
    TextBox txtFirstName  
    Label   Last Name:
    TextBox txtLastName  
    Label   Full Name:
    TextBox txtFullName  
  5. Return to Microsoft Excel
  6. Save the file with the name Conditions1 as a Macro-Enabled Workbook
  7. Return to Microsoft Visual Basic
  8. Right-click the form and click View Code

If a Condition is True/False, Then What?

The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:

If ConditionToCheck Then Statement

Therefore, the program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement.

There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:

If ConditionToCheck Then Statement

Here is an example:

Sub Exercise()
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 33.0
    MsgBox("Tax Rate: " & TaxRate & "%")

    IsMarried = True

    If IsMarried = True Then TaxRate = 30.65

    MsgBox("Tax Rate: " & TaxRate & "%")
End Sub

This would produce:

If Condition If Condition

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. If you write the conditional statement in more than one line, you must end it with End If on its own line. The formula used is:

If ConditionToCheck Then
    Statement
End If

Here is an example:

Sub Exercise()
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 33#

    MsgBox ("Tax Rate: " & TaxRate & "%")

    IsMarried = True
    
    If IsMarried = True Then
        TaxRate = 30.65

        MsgBox ("Tax Rate: " & TaxRate & "%")
    End If
End Sub

Practical Learning: Using If...Then

  1. In the Variant combo box, select txtFirstName and change its Change event as follows:
     
    Private Sub txtFirstName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        
        FullName = LastName & ", " & FirstName
        
        txtFullName.Text = FullName
        If LastName = "" Then txtFullName.Text = FirstName
    End Sub
  2. In the Variant combo box, select txtLastName and change its Change event as follows:
     
    Private Sub txtLastName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        
        FullName = LastName & ", " & FirstName
        
        txtFullName.Text = FullName
        If LastName = "" Then txtFullName.Text = FirstName
    End Sub
  3. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
  4. Click the top text box and type Julienne. Notice that only the first name displays in the Full Name text box
     
  5. Press Tab
  6. In the other text box, start typing Pal and notice that the Full Name text box is changing
  7. Complete it with Palace
  8. Close the form and return to Microsoft Visual Basic

Using the Default Value of a Boolean Expression

In the previous lesson, we saw that when you declare a Boolean variable, by default, it is initialized with the False value. Here is an example:

Module Exercise

    Sub Exercise
        Dim IsMarried As Boolean

        MsgBox("Employee Is Married? " & IsMarried)
        
        Return 0
    End Function

End Module

This would produce:

Boolean Variable

Based on this, if you want to check whether a newly declared and uninitialized Boolean variable is false, you can omit the = False expression applied to it. Here is an example:

Sub Exercise()
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 33#

    If IsMarried Then TaxRate = 30.65

    MsgBox ("Tax Rate: " & TaxRate & "%")
End Sub

This would produce:

Boolean Variable

Notice that there is no = after the If IsMarried expression. In this case, the value of the variable is False. On the other hand, if you want to check whether the variable is True, make sure you include the = True expression. Overall, whenever in doubt, it is safer to always initialize your variable and it is safer to include the = True or = False expression when evaluating the variable:

Sub Exercise()
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 36.45 ' %

    IsMarried = True

    If IsMarried = False Then TaxRate = 33.15

    MsgBox ("Tax Rate: " & TaxRate & "%")
End Sub

In the previous lesson, we introduced some Boolean-based functions such as IsNumeric and IsDate. The default value of these functions is True. This means that when you call them, you can omit the = True expression.

What Else When a Condition is True/False?

 

The If...Then...Else Condition

The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is:

If ConditionToCheck Then
    Statement1
Else
    Statement2
End If

When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

Here is an example:

Sub Exercise()
    Dim MemberAge As Integer
    Dim MemberCategory As String

    MemberAge = 16

    If MemberAge <= 18 Then
        MemberCategory = "Teen"
    Else
        MemberCategory = "Adult"
    End If

    MsgBox ("Membership: " & MemberCategory)
End Sub

This would produce:

If...Then...Else

Practical Learning: Using If...Then...Else

  1. Change the codes of both events as follows:
     
    Private Sub txtFirstName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        
        If LastName = "" Then
            FullName = FirstName
        Else
            FullName = LastName & ", " & FirstName
        End If
        
        txtFullName.Text = FullName
    End Sub
    
    Private Sub txtLastName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        
        If FirstName = "" Then
            FullName = LastName
        Else
            FullName = LastName & ", " & FirstName
        End If
        
        txtFullName.Text = FullName
    End Sub
  2. Press F5 to test the form
  3. After using the form, close it and return to Visual Basic
 

 

 

Immediate If

To assist you with checking a condition and its alternative, the Visual Basic language provides a function named IIf. Its syntax is:

Public Function IIf( _
   ByVal Expression As Boolean, _ 
   ByVal TruePart As Variant, _ 
   ByVal FalsePart As Variant _ 
) As Variant

This function operates like an If...Then...Else condition. It takes three required arguments and returns a result of type Variant. This returned value will hold the result of the function.

The condition to check is passed as the first argument:

  • If that condition is true, the function returns the value of the TruePart argument and the last argument is ignored
  • If the condition is false, the first argument is ignored and the function returns the value of the second argument

As mentioned already, you can retrieved the value of the right argument and assign it to the result of the function. The expression we saw early can be written as follows:

Sub Exercise()
    Dim MemberAge As Integer
    Dim MemberCategory As String

    MemberAge = 16

    MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult")

    MsgBox ("Membership: " & MemberCategory)
End Sub

This would produce the same result we saw earlier.

Practical Learning: Introducing Select Cases

  1. From the resources that accompany these lessons, open the gdcs1 (or gdcs2) workbook
  2. To open Microsoft Visual Basic, on the Ribbon, click Developer and, in the Code section, click Visual Basic:
     
    Georgetown Dry Cleaning Services
  3. Right-click the form and click View Code
  4. Click under any code and type the following:
     
    Private Sub CalucateOrder()
        Dim UnitPriceShirts As Double, UnitPricePants As Double
        Dim UnitPriceItem1 As Double, UnitPriceItem2 As Double
        Dim UnitPriceItem3 As Double, UnitPriceItem4 As Double
        Dim QuantityShirts As Integer, QuantityPants As Integer
        Dim QuantityItem1 As Integer, QuantityItem2 As Integer
        Dim QuantityItem3 As Integer, QuantityItem4 As Integer
        Dim SubTotalShirts As Double, SubTotalPants As Double
        Dim SubTotalItem1 As Double, SubTotalItem2 As Double
        Dim SubTotalItem3 As Double, SubTotalItem4 As Double
        Dim CleaningTotal As Double, TaxRate As Double
        Dim TaxAmount As Double, OrderTotal As Double
        
        UnitPriceShirts = 0#: UnitPricePants = 0#
        UnitPriceItem1 = 0#: UnitPriceItem2 = 0#
        UnitPriceItem3 = 0#: UnitPriceItem4 = 0#
        
        QuantityShirts = 0: QuantityPants = 0
        QuantityItem1 = 0:  QuantityItem2 = 0
        QuantityItem3 = 0:   QuantityItem4 = 0
        
        TaxRate = 0
        
        UnitPriceShirts = IIf(IsNumeric(txtUnitPriceShirts), _
                              CDbl(txtUnitPriceShirts), 0)
        
        UnitPricePants = IIf(IsNumeric(txtUnitPricePants), _
                             CDbl(txtUnitPricePants), 0)
        
        UnitPriceItem1 = IIf(IsNumeric(txtUnitPriceItem1), _
                             CDbl(txtUnitPriceItem1), 0)
        
        UnitPriceItem2 = IIf(IsNumeric(txtUnitPriceShirts), _
                             CDbl(txtUnitPriceItem2), 0)
        
        UnitPriceItem3 = IIf(IsNumeric(txtUnitPriceShirts), _
                             CDbl(txtUnitPriceItem3), 0)
        
        UnitPriceItem4 = IIf(IsNumeric(txtUnitPriceShirts), _
                             CDbl(txtUnitPriceItem4), 0)
        
        
        QuantityShirts = IIf(IsNumeric(txtUnitPriceShirts), _
                             CInt(txtQuantityShirts), 0)
        
        QuantityPants = IIf(IsNumeric(txtQuantityPants), _
                             CInt(txtQuantityPants), 0)
        
        QuantityItem1 = IIf(IsNumeric(txtQuantityItem1), _
                             Int(txtQuantityItem1), 0)
        
        QuantityItem2 = IIf(IsNumeric(txtQuantityItem2), _
                             CInt(txtQuantityItem2), 0)
        
        QuantityItem3 = IIf(IsNumeric(txtQuantityItem3), _
                             CInt(txtQuantityItem3), 0)
        
        QuantityItem4 = IIf(IsNumeric(txtQuantityItem4), _
                             CInt(txtQuantityItem4), 0)
        
        TaxRate = IIf(IsNumeric(txtTaxRate), _
                             CDbl(txtTaxRate), 0)
        
        SubTotalShirts = UnitPriceShirts * QuantityShirts
        SubTotalPants = UnitPricePants * QuantityPants
        SubTotalItem1 = UnitPriceItem1 * QuantityItem1
        SubTotalItem2 = UnitPriceItem2 * QuantityItem2
        SubTotalItem3 = UnitPriceItem3 * QuantityItem3
        SubTotalItem4 = UnitPriceItem4 * QuantityItem4
        
        txtSubTotalShirts = FormatNumber(SubTotalShirts)
        txtSubTotalPants = FormatNumber(SubTotalPants)
        txtSubTotalItem1 = FormatNumber(SubTotalItem1)
        txtSubTotalItem2 = FormatNumber(SubTotalItem2)
        txtSubTotalItem3 = FormatNumber(SubTotalItem3)
        txtSubTotalItem4 = FormatNumber(SubTotalItem4)
        
        CleaningTotal = SubTotalShirts + SubTotalPants + _
                        SubTotalItem1 + SubTotalItem2 + _
                        SubTotalItem3 + SubTotalItem4
        
        TaxAmount = CleaningTotal * TaxRate / 100
        OrderTotal = CleaningTotal + TaxAmount
        
        txtCleaningTotal = FormatNumber(CleaningTotal)
        txtTaxAmount = FormatNumber(TaxAmount)
        txtOrderTotal = FormatNumber(OrderTotal)
    End Sub
    
    Private Sub txtUnitPriceShirts_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityShirts_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtUnitPricePants_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityPants_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtUnitPriceItem1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityItem1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtUnitPriceItem2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityItem2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtUnitPriceItem3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityItem3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtUnitPriceItem4_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtQuantityItem4_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
    
    Private Sub txtTaxRate_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        CalucateOrder
    End Sub
  5. Close Microsoft Visual Basic
  6. Save the workbook 

Choosing a Value

We have learned how to check whether a condition is True or False and take an action. Here is an example:

Sub Exercise()
    Dim Status As Integer, EmploymentStatus As String

    Status = 1
    EmploymentStatus = "Unknown"

    If Status = 1 Then
        EmploymentStatus = "Full Time"
    End If

    MsgBox ("Employment Status: " & EmploymentStatus)
End Sub

To provide an alternative to this operation, the Visual Basic language provides a function named Choose. Its syntax is:

Public Function Choose( _
   ByVal Index As Double, _ 
   ByVal ParamArray Choice() As Variant _
) As Variant

This function takes two required arguments. The fist argument is equivalent to the ConditionToCheck of our If...Then formula. For the Choose() function, this first argument must be a number. This is the value against which the second argument will be compared. Before calling the function, you must know the value of the first argument. To take care of this, you can first declare a variable and initialize it with the desired value. Here is an example:

Sub Exercise()
    Dim Status As Byte, EmploymentStatus As String

    Status = 1

    EmploymentStatus = Choose(Status, ...)

    MsgBox ("Employment Status: " & EmploymentStatus)
End Sub

The second argument can be the Statement of our formula. Here is an example:

Choose(Status, "Full Time")

We will see in the next sections that the second argument is actually a list of values and each value has a specific position referred to as its index. To use the function in an If...Then scenario, you pass only one value as the second argument. This value/argument has an index of 1. When the Choose() function is called in an If...Then implementation, if the first argument holds a value of 1, the second argument is validated.

When the Choose() function has been called, it returns a value of type Variant. You can retrieve that value, store it in a variable and use it as you see fit. Here is an example:

Sub Exercise()
    Dim Status As Byte, EmploymentStatus As String

    Status = 1

    EmploymentStatus = Choose(Status, "Full Time")

    MsgBox ("Employment Status: " & EmploymentStatus)
End Sub

This would produce:

Choose

In some cases, the Choose() function can produce a null result. Consider the same program we used earlier but with a different value:

Module Exercise

    Sub Exercise
        Dim Status As Integer, EmploymentStatus As String

        Status = 2

        EmploymentStatus = Choose(Status, "Full Time")

        MsgBox(EmploymentStatus)

        Return 0
    End Function

End Module

This would produce an error because there is no value in index 2 after the Status variable has been initialized with 2. To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. The second argument is actually passed as a list of values. Each value has a specific position as its index. To use the function in an If...Then...Else implementation, pass two values for the second argument. Here is an example:

Choose(Status, "Full Time", "Part Time")

The second argument to the function, which is the first value of the Choose argument, has an index of 1. The third argument to the function, which is the second value of the Choose argument, has an index of 2. 

When the Choose() function is called, if the first argument has a value of 1, then the second argument is validated. If the first argument has a value of 2, then the third argument is validated. As mentioned already, you can retrieve the returned value of the function and use it however you want. Here is an example:

Sub Exercise()
    Dim Status As Integer, EmploymentStatus As String

    Status = 2

    EmploymentStatus = Choose(Status, "Full Time", "Part Time")

    MsgBox ("Employment Status: " & EmploymentStatus)
End Sub

This would produce:

Choose

Switching to a Value

As another alternative to an If...Then condition, the Visual Basic language provides a function named Switch. Its syntax is:

Public Function Switch( _
    ByVal ParamArray VarExpr() As Variant _
) As Variant

This function takes one required argument. To use it in an If...Then scenario, pass the argument as follows:

Switch(ConditionToCheck, Statement)

In the ConditionToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed.

When the Switch() function has been called, it produces a value of type Variant (such as a string) that you can use as you see fit. For example, you can store it in a variable. Here is an example:

Sub Exercise()
    Dim Status As Integer, EmploymentStatus As String

    Status = 1
    EmploymentStatus = "Unknown"

    EmploymentStatus = Switch(Status = 1, "Full Time")

    MsgBox ("Employment Status: " & EmploymentStatus)
End Sub

In this example, we used a number as argument. You can also use another type of value, such as an enumeration. Here is an example:

Private Enum EmploymentStatus
    FullTime
    PartTime
    Contractor
    Seasonal
    Unknown
End Enum
        
Sub Exercise()
    Dim Status As EmploymentStatus
    Dim Result As String

    Status = EmploymentStatus.FullTime
    Result = "Unknown"

    Result = Switch(Status = EmploymentStatus.FullTime, "Full Time")

    MsgBox ("Employment Status: " & Result)
End Sub

When using the Switch function, if you call it with a value that is not checked by the first argument, the function produces an error. To apply this function to an If...Then...Else scenario, you can call it using the following formula:

Switch(Condition1ToCheck, Statement1, Condition2ToCheck, Statement2)

In the Condition1ToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed. To provide an alternative to the first condition, pass another condition as Condition2ToCheck. If the Condition2ToCheck is true, then Statement2 would be executed. Once gain, remember that you can get the value returned by the Switch function and use it. Here is an example:

Private Enum EmploymentStatus
    FullTime
    PartTime
    Contractor
    Seasonal
    Unknown
End Enum
        
Sub Exercise()
    Dim Status As EmploymentStatus
    Dim Result As String

    Status = EmploymentStatus.PartTime
    Result = "Unknown"

    Result = Switch(Status = EmploymentStatus.FullTime, "Full Time", _
                    Status = EmploymentStatus.PartTime, "Part Time")

    MsgBox ("Employment Status: " & Result)
End Sub

This would produce:

Choose

 
 
   
 

Previous Copyright © 2008-2016, FunctionX, Inc. Next