Home

Functional Conditions

 

Alternatives to a Condition Being True/False?

 

The If...Then...ElseIf Condition

The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
End If

The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one that is true. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If. Here is an example:

Sub Exercise()
    Dim MemberAge As Byte

    MemberAge = 32

    If MemberAge <= 18 Then
        MsgBox ("Membership: " & "Teen")
    ElseIf MemberAge < 55 Then
        MsgBox ("Membership: " & "Adult")
    End If
End Sub

This would produce:

If Condition

Practical LearningPractical Learning: Introducing Data Entry

  1. Start Microsoft Excel and, on the Ribbon, click Developer
  2. In the Code section, click Visual Basic
  3. To add a new form, on the Standard toolbar, click the Insert UserForm button
  4. Design the form as follows:
     
    Form Design: CD Publisher
    Control Name Caption/Text Other Properties
    Label Number of CDs:  
    TextBox txtQuantity 0 TextAlign: 3 - frmTextAlignRight
    CommandButton cmdEvaluate Evaluate  
    Frame   Based on the Specified Quantity  
    Label   Each CD will cost:  
    TextBox txtUnitPrice 0.00 TextAlign: 3 - frmTextAlignRight
    Label   And the total price is:  
    TextBox txtTotalPrice 0.00 TextAlign: 3 - frmTextAlignRight

What If No Alternative is Valid?

There is still a possibility that none of the stated conditions be true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
Else
    CatchAllStatement
End If

Here is an example:

Sub Exercise()
    Dim MemberAge As Byte

    MemberAge = 65

    If MemberAge <= 18 Then
        MsgBox ("Membership: " & "Teen")
    ElseIf MemberAge < 55 Then
        MsgBox ("Membership: " & "Adult")
    Else
        MsgBox ("Membership: " & "Senior")
    End If
End Sub

This would produce:

Else

 

Practical Learning: Using If...Then...ElseIf

  1. Double-click the Evaluate button and implement its Click event as follows:
     
    Private Sub cmdEvaluate_Click()
        Dim Quantity As Integer
        Dim UnitPrice As Currency
        Dim TotalPrice As Currency
        
        Quantity = CInt(txtQuantity.Text)
        
        ' The price of one CD will depend on the number ordered
        ' The more the customer orders, the lower value each
        If Quantity < 20 Then
            UnitPrice = 20
        ElseIf Quantity < 50 Then
            UnitPrice = 15
        ElseIf Quantity < 100 Then
            UnitPrice = 12
        ElseIf Quantity < 500 Then
            UnitPrice = 8
        Else
            UnitPrice = 5
        End If
            
        TotalPrice = Quantity * UnitPrice
    
        txtUnitPrice.Text = CStr(UnitPrice)
        txtTotalPrice.Text = CStr(TotalPrice)
    End Sub
  2. Press F5 to test the form
  3. Perform the calculations with different quantities. For example, in the top text box, type 1250 and click Evaluate
     
    CD Publisher
  4. After testing various quantities, close the form

Conditional Statements and Functions

 

Introduction

As introduced in previous lessons, we know that a function is used to perform a specific assignment and produce a result. Here is an example:

Private Function SetMembershipLevel$()
    Dim MemberAge%

    MemberAge% = InputBox("Enter the Member's Age")

    SetMembershipLevel$ = ""
End Function

When performing its assignment, a function can encounter different situations, some of which would need to be checked for truthfulness or negation. This means that conditional statements can assist a procedure with its assignment.

 

Practical Learning: Introducing Condition Functions

  1. Start another workbook
  2. In cell B2, type Bethesda Car Rental
  3. In cell B3, type Order Processing
  4. In cell B4, type Processed by:
  5. In cell B5, type Processed for:
  6. In cell B6, type Car Selected
  7. In cell B7, type Tag #:
  8. Enlarge column B so that Processed by: can fit in the allocated width
  9. Right-align cell B7

Bethesda Car Rental

Conditional Returns

A function is meant to return a value. Sometimes, it will perform some tasks whose results would lead to different results. A function can return only one value (we saw that, by passing arguments by reference, you can make a procedure return more than one value) but you can make it render a result depending on a particular behavior. If a function is requesting an answer from the user, since the user can provide different answers, you can treat each result differently. Consider the following function:

Private Function SetMembershipLevel$()
    Dim MemberAge%

    MemberAge% = InputBox("Enter the Member's Age")

    If MemberAge% < 18 Then
        SetMembershipLevel$ = "Teen"
    ElseIf MemberAge% < 55 Then
        SetMembershipLevel$ = "Adult"
    End If
End Function

Sub Exercise()
    Dim Membership$

    MsgBox ("Membership: " & Membership$)
End Sub

At first glance, this function looks fine. The user is asked to provide a number. If the user enters a number less than 18 (excluded), the function returns Teen. Here is an example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

If the user provides a number between 18 (included) and 55, the function returns the Adult. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

What if there is an answer that does not fit those we are expecting? The values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in If Condidion Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user enters a number higher than 55 (excluded), the function will not execute any of the returned statements. This means that the execution will reach the End Function line without encountering a return value. This also indicates to the compiler that you wrote a function that is supposed to return a value, but by the end of the method, it didn't return a value. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

To solve this problem, you have various alternatives. If the function uses an If...Then condition, you can create an Else section that embraces any value other than those validated previously. Here is an example:

Private Function SetMembershipLevel$()
    Dim MemberAge%

    MemberAge% = InputBox("Enter the Member's Age")

    If MemberAge% < 18 Then
        SetMembershipLevel$ = "Teen"
    ElseIf MemberAge% < 55 Then
        SetMembershipLevel$ = "Adult"
    Else
        SetMembershipLevel$ = "Senior"
    End If
End Function

Sub Exercise()
    Dim Membership$

    Membership$ = SetMembershipLevel$()
    MsgBox ("Membership: " & Membership$)
End Sub

This time, the Else condition would execute if no value applies to the If or ElseIf conditions and the compiler would not produce a warning. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

An alternative is to provide a last return value just before the End Function line. In this case, if the execution reaches the end of the function, it would still return something but you would know what it returns. This would be done as follows:

Private Function SetMembershipLevel$()
    Dim MemberAge%

    MemberAge% = InputBox("Enter the Member's Age")

    If MemberAge% < 18 Then
        SetMembershipLevel$ = "Teen"
    ElseIf MemberAge% < 55 Then
        SetMembershipLevel$ = "Adult"
    End If

    SetMembershipLevel$ = "Senior"
End Function

If the function uses an If condition, both implementations would produce the same result.

Practical LearningPractical Learning: Using a Conditional Statement

  1. On the Ribbon, click Developer
  2. In the Code section, click Record Macro
  3. Set the Macro Name to LocateEmployee
  4. In the Shortcut Key text box, type E to get Ctrl + Shift + E
     
    Record Macro
  5. Click OK
  6. On the Ribbon, click Stop Recording
  7. In the Code section of the Ribbon, click Macros Macros
  8. In the Macro dialog box, make sure LocateEmployee is selected and click Edit
  9. Change the code as follows:
     
    Private Function GetEmployeeName(ByVal EmplNbr As Long) As String
        Dim Name As String
    
        If EmplNbr = 22804 Then
            Name = "Helene Mukoko"
        ElseIf EmplNbr = 92746 Then
            Name = "Raymond Kouma"
        ElseIf EmplNbr = 54080 Then
            Name = "Henry Larson"
        ElseIf EmplNbr = 86285 Then
            Name = "Gertrude Monay"
        Else
            Name = ""
        End If
    
        GetEmployeeName = Name
    End Function
    
    Public Sub LocateEmployee()
    '
    ' Macro Name: LocateEmployee
    ' This macro is used to find the name of an employee
    ' based on the employee number
    '
    ' Keyboard Shortcut: Ctrl+Shift+E
    '
        Dim EmployeeNumber As Long, EmployeeName As String
        
        If IsEmpty(Range("C4")) Then
            MsgBox "You must enter the employee number in cell C4"
            Range("D4").FormulaR1C1 = ""
            EmployeeNumber = 0
        Else
            EmployeeNumber = CLng(Range("C4"))
        End If
        
        EmployeeName = GetEmployeeName(EmployeeNumber)
        Range("D4").FormulaR1C1 = EmployeeName
    End Sub
  10. Return to Microsoft Excel
  11. In cell C4, type 54080 and press Enter
  12. Press Ctrl + Shift + E to see the result

Bethesda Car Rental

 

 

 
 

If-Condition Built-In Functions

 

Using the Immediate If Function

The IIf() function can also be used in place of an If...Then...ElseIf scenario. When the function is called, the Expression is checked. As we saw already, if the expression is true, the function returns the value of the TruePart argument and ignores the last argument. To use this function as an alternative to If...Then...ElseIf statement, if the expression is false, instead of immediately returning the value of the FalsePart argument, you can translate that part into a new IIf function. The pseudo-syntax would become:

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

In this case, if the expression is false, the function returns the TruePart and stops. If the expression is false, the compiler accesses the internal IIf function and applies the same scenario. Here is example:

Sub Exercise()
    Dim MemberAge As Byte
    Dim MembershipCategory As String

    MemberAge = 74

    MembershipCategory = _
    IIf(MemberAge <= 18, "Teen", IIf(MemberAge < 55, "Adult", "Senior"))

    MsgBox ("Membership: " & MembershipCategory)
End Sub

We saw that in an If...Then...ElseIf statement you can add as many ElseIf conditions as you want. In the same, you can call as many IIf functions in the subsequent FalsePart sections as you judge necessary:

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

Choose an Alternate Value

As we have seen so far, the Choose function takes a list of arguments. To use it as an alternative to the If...Then...ElseIf...ElseIf condition, you can pass as many values as you judge necessary for the second argument. The index of the first member of the second argument would be 1. The index of the second member of the second argument would be 2, and so on. When the function is called, it would first get the value of the first argument, then it would check the indexes of the available members of the second argument. The member whose index matches the first argument would be executed. Here is an example:

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

    Status = 3

    EmploymentStatus = Choose(Status, _
                              "Full Time", _
                              "Part Time", _
                              "Contractor", _
                              "Seasonal")

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

This would produce:

Choose

So far, we have used only strings for the values of the second argument of the Choose() function. In reality, the values of the second argument can be almost anything. One value can be a constant. Another value can be a string. Yet another value can come from calling a function. Here is an example:

Private Function ShowContractors$()
    ShowContractors$ = "=-= List of Contractors =-=" & vbCrLf & _
                       "Martin Samson" & vbCrLf & _
                       "Geneviève Lam" & vbCrLf & _
                       "Frank Viel" & vbCrLf & _
                       "Henry Rickson" & vbCrLf & _
                       "Samuel Lott"
End Function

Sub Exercise()
    Dim Status As Byte, Result$

    Status = 3

    Result = Choose(Status, _
                    "Employment Status: Full Time", _
                    "Employment Status: Part Time", _
                    ShowContractors, _
                    "Seasonal Employment")
    MsgBox (Result)
End Sub

This would produce:

Choose

The values of the second argument can even be of different types.

Switching to an Alternate Value

The Switch() function is a prime alternative to the If...Then...ElseIf...ElseIf condition. The argument to this function is passed as a list of values. As seen previously, each value is passed as a combination of two values:

ConditionXToCheck, StatementX

As the function is accessed, the compiler checks each condition. If a condition X is true, its statement is executed. If a condition Y is false, the compiler skips it. You can provide as many of these combinations as you want. Here is an example:

Private Enum EmploymentStatus
    FullTime
    PartTime
    Contractor
    Seasonal
End Enum

Sub Exercise()
    Dim Status As EmploymentStatus
    Dim Result As String

    Status = EmploymentStatus.Contractor
    Result = "Unknown"

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

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

This would produce:

Switch

In a true If...Then...ElseIf...ElseIf condition, we saw that there is a possibility that none of the conditions would fit, in which case you can add a last Else statement. The Switch() function also supports this situation if you are using a number, a character, or a string. To provide this last alternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessary statement. Here is an example:

Sub Exercise()
    Dim Status As Byte
    Dim Result As String

    Status = 12

    Result = Switch(Status = 1, "Full Time", _
                    Status = 2, "Part Time", _
                    Status = 3, "Contractor", _
                    Status = 4, "Seasonal", _
                    True, "Unknown")

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

This would produce:

Switch

Remember that you can also use True with a character. Here is an example:

Sub Exercise()
    Dim Gender As String
    Dim Result As String

    Gender = "H"

    Result = Switch(Gender = "f", "Female", _
                    Gender = "F", "Female", _
                    Gender = "m", "Male", _
                    Gender = "M", "Male", _
                    True, "Unknown")

    MsgBox ("Gender: " & Result)
End Sub

This would produce:

Switch

Practical LearningPractical Learning: Using the Switch() Function

  1. In the Code section, click Record Macro
  2. Set the Macro Name to SelectCar
  3. In the Shortcut Key text box, type S to get Ctrl + Shift + S, and click OK
  4. On the Ribbon, click Stop Recording
  5. In the Code section of the Ribbon, click Macros Macros
  6. In the Macro dialog box, make sure FindEmployee is selected and click Edit
  7. To use the Switch() function, change the document as follows:
     
    Public Sub SelectCar()
    '
    ' Macro Name: SelectCar
    ' This macro is used to locate a car given its tag number
    ' Keyboard Shortcut: Ctrl+Shift+S
    '
        Dim TagNumber As String, CarSelected As String
        
        If IsEmpty(Range("C7")) Then
            MsgBox "You must enter the tag number of the car the customer will rent"
            TagNumber = 0
        Else
            TagNumber = Range("C7")
        
            CarSelected = Switch(TagNumber = "297419", "BMW 335i", _
                                 TagNumber = "485M270", "Chevrolet Avalanche", _
                                 TagNumber = "247597", "Honda Accord LX", _
                                 TagNumber = "924095", "Mazda Miata", _
                                 TagNumber = "772475", "Chevrolet Aveo", _
                                 TagNumber = "M931429", "Ford E150XL", _
                                 TagNumber = "240759", "Buick Lacrosse", _
                                 True, "Unidentified Car")
                                 
            Range("D7").FormulaR1C1 = CarSelected
        End If
  8. Return to Microsoft Excel
  9. In cell C7, type 924095 and press Enter
  10. Press Ctrl + Shift + S to see the result

Bethesda Car Rental

 
 
   
 

Previous Copyright © 2008-2010 FunctionX, Inc. Next