Microsoft Access Database Development With VBA

Conditional Counting and Looping

 

The Select Case Statement

 

Introduction

If you have a large number of conditions to examine, the If...Then...Else statement will go through each one of them. The Visual Basic language offers the alternative of jumping to the statement that applies to the state of a condition. This is referred to as a select case condition. It uses the keywords Select and Case.

The formula of the Select Case statement is:

Select Case Expression
    Case Expression1
	Statement1
    Case Expression2
        Statement2
    Case Expression_X
        Statement_X
End Select

The statement starts with Select Case and ends with End Select. On the right side of Select Case, enter a value, the Expression factor, that will be used as a tag. The value of Expression can be a Boolean value (a Boolean type), a character or a string (a String type), a natural number (a Byte, an Integer, or a Long type), a decimal number (a Single or a Double type), a date or time value (a Date type), an enumeration (an Enum type), or else (a Variant type).

Inside the Select Case and the End Select lines, you provide one or more sections that each contains a Case keyword followed by a value. The value on the right side of a Case, Expresion1, Expresion2, or Expresion_X, must be the same type as the value of Expression or it can be implied from it. After the case and its expression, you can write a statement.

When this section of code is accessed, the value of Expression is considered. Then the value of Expression is compared to each Expression_X of each case:

  1. If the value of Expression1 is equal to that of Expression, then Statement1 is executed.
    If the value of Expression1 is not equal to that of Expression, then the interpreter moves to Expression2
  2. If the value of Expression2 is equal to that of Expression, then Statement2 is executed
  3. This will continue down to the last Expression_X

Here is an example:

Private Sub cmdFunction_Click()
    Dim Answer As Byte

    Answer = CByte(InputBox( _
                  "One of the following is not a Visual Basic keyword" & vbCrLf & _
                     "1) Function" & vbCrLf & _
                     "2) Except" & vbCrLf & _
                     "3) ByRef" & vbCrLf & _
                     "4) Each" & vbCrLf & vbCrLf & _
                     "Your Answer? "))

    Select Case Answer
        Case 1
            MsgBox("Wrong: Function is a Visual Basic keyword." & vbCrLf & _
                   "It is used to create a procedure of a function type")
        Case 2
            MsgBox("Correct: Except is not a keyword in " & vbCrLf & _
                   "Visual Basic but __except is a C++ " & vbCrLf & _
                   "keyword used in Exception Handling")
        Case 3
            MsgBox("Wrong: ByRef is a Visual Basic keyword used " & vbCrLf & _
                   "to pass an argument by reference to a procedure")
        Case 4
            MsgBox("Wrong: The ""Each"" keyword is used in " & vbCrLf & _
                   "Visual Basic in a type of looping " & vbCrLf & _
                   "used to ""scan"" a list of item.")
    End Select
End Sub

Here is an example of running the program:

Select

Select

What Case Else?

The above code supposes that one of the cases will match the value of the Expression factor. This is not always so. If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
    Case Else
        Statementk
End Select

In this case, the statement after the Case Else will execute if none of the previous expressions matches the Expression factor. Here is an example:

Private Sub cmdFunction_Click()
    Dim Answer As Byte

    Answer = CByte(InputBox( _
                   "One of the following is not a Visual Basic keyword" & vbCrLf & _
                   "1) Function" & vbCrLf & _
                   "2) Except" & vbCrLf & _
                   "3) ByRef" & vbCrLf & _
                   "4) Each" & vbCrLf & vbCrLf & _
                   "Your Answer? "))

    Select Case Answer
        Case 1
            MsgBox("Wrong: Function is a Visual Basic keyword." & vbCrLf & _
                   "It is used to create a procedure of a function type")
        Case 2
            MsgBox("Correct: Except is not a keyword in " & vbCrLf & _
                   "Visual Basic but __except is a C++ " & vbCrLf & _
                   "keyword used in Exception Handling")
        Case 3
            MsgBox("Wrong: ByRef is a Visual Basic keyword used " & vbCrLf & _
                   "to pass an argument by reference to a procedure")
        Case 4
            MsgBox("Wrong: The ""Each"" keyword is used in " & vbCrLf & _
                   "Visual Basic in a type of looping " & vbCrLf & _
                   "used to ""scan"" a list of item.")
        Case Else
            MsgBox("Invalid Selection")
    End Select
End Sub

Here is an example of running the program:

Select

Select

Combining Cases

As mentioned in our introduction, the Select Case can use a value other than an integer. For example you can use a character:

Private Sub cmdFunction_Click()
    Dim Gender As String

    Gender = "M"

    Select Case Gender
        Case "F"
            MsgBox("Female")
        Case "M"
            MsgBox("Male")
        Case Else
            MsgBox("Unknown")
    End Select
End Sub

This would produce:

Select

Notice that in this case we are using only upper case characters. If want to validate lower case characters also, we may have to create additional case sections for each. Here is an example:

Private Sub cmdFunction_Click()
    Dim Gender As String

    Gender = "f"

    Select Case Gender
        Case "f"
            MsgBox("Female")
        Case "F"
            MsgBox("Female")
        Case "m"
            MsgBox("Male")
        Case "M"
            MsgBox("Male")
        Case Else
            MsgBox("Unknown")
    End Select
End Sub

This would produce:

Select

Instead of using one value for a case, you can apply more than one. To do this, on the right side of the Case keyword, you can separate the expressions with commas. Here are examples:

Private Sub cmdFunction_Click()
    Dim Gender As String

    Gender = "F"

    Select Case Gender
        Case "f", "F"
            MsgBox("Female")
        Case "m", "M"
            MsgBox("Male")
        Case Else
            MsgBox("Unknown")
    End Select
End Sub

Validating a Range of Cases

You can use a range of values for a case. To do this, on the right side of a Case, enter the lower value, followed by To, followed by the higher value. Here is an example:

Private Sub cmdFunction_Click()
    Dim Age As Integer
    Age = 24

    Select Case Age
        Case 0 To 17
            MsgBox("Teen")
        Case 18 To 55
            MsgBox("Adult")
        Case Else
            MsgBox("Senior")
    End Select
End Sub

This would produce:

Select

Checking Whether a Value IS

Consider the following procedure:

Private Sub cmdFunction_Click()
    Dim Number As Integer

    Number = 448

    Select Case Number
        Case -602
            MsgBox "-602"
        Case 24
            MsgBox "24"
        Case 0
            MsgBox "0"
    End Select
End Sub

Obviously, this Select Case statement will work in rare cases only when the expression of a case exactly matches the value sought for. In reality, for this type of scenario, you could validate a range of values. The Visual Basic language provides an alternative. You can check whether the value of the Expression responds to a criterion instead of an exact value. To create it, you use the Is operator with the following formula:

Is Operator Value

You start with the Is keyword. It is followed by one of the Boolean operators we know already: =, <>, <, <=, >, or >=. On the right side of the Boolean operator, type the desired value. Here are examples:

Private Sub cmdFunction_Click()
    Dim Number As Integer

    Number = -448

    Select Case Number
        Case Is < 0
            MsgBox("The number is negative")
        Case Is > 0
            MsgBox("The number is positive")
        Case Else
            MsgBox("0")
    End Select
End Sub

This would produce:

Select

Although we used a natural number here, you can use any appropriate logical comparison that can produce a True or a False result. You can also combine it with the other alternatives we saw previously, such as separating the expressions of a case with commas.

Select...Case and the Conditional Built-In Functions

With the Select...Case statement, we saw how to check different values against a central one and take action when one of those matches the tag. Here is an example:

Private Sub cmdFunction_Click()
    Dim Number As Integer, MembershipType As String

    Number = 2

    Select Case Number
        Case 1
            MembershipType = "Teen"
        Case 2
            MembershipType = "Adult"
        Case Else
            MembershipType = "Senior"
    End Select

    MsgBox "Membership Type: " & MembershipType
End Sub

This would produce:

Select

Select...Case-Related Functions: Choose()

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

Private Sub cmdFunction_Click()
    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:

Private Sub cmdFunction_Click()
    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")

The second argument is actually a list of values and each value has a specific position referred to as its index. To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. 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:

Private Sub cmdFunction_Click()
    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

To use the Choose function 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:

Private Sub cmdFunction_Click()
    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

Private Sub cmdFunction_Click()
    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.

 

 

 
 
 

Practical LearningPractical Learning: Using the Choose Function

  1. Start Microsoft Access
  2. From the resources that accompany these lessons, open the Exercise3 database
  3. In the Navigation Pane, right-click the Compound Interest form and click Design View:
     
    Compound Interest
  4. On the form, right-click the Calculate button and click Build Event...
  5. In the Choose Builder dialog box, double-click Code Builder
  6. Implement the Click event as follows:
    Private Sub cmdCalculate_Click()
        Dim Principal As Currency
        Dim InterestRate As Double
        Dim InterestEarned As Currency
        Dim FutureValue As Currency
        Dim RatePerPeriod As Double
        Dim Periods As Integer
        Dim CompoundType As Integer
        Dim i As Double
        Dim n As Integer
        
        Principal = CCur(txtPrincipal)
        InterestRate = CDbl(txtInterestRate)
        
        CompoundType = Choose([fraFrequency], 12, 4, 2, 1)
        
        Periods = CInt(txtPeriods)
        i = InterestRate / CompoundType
        n = CompoundType * Periods
        RatePerPeriod = InterestRate / Periods
        FutureValue = Principal * ((1 + i) ^ n)
        InterestEarned = FutureValue - Principal
        
        txtInterestEarned = CStr(InterestEarned)
        txtAmountEarned = CStr(FutureValue)
    End Sub
  7. Return to Microsoft Access and switch the form to Form View
  8. Click Principal and type 8500
  9. Click Interest Rate, type 9.25
  10. Click Periods and type 2
  11. Click the Quarterly radio button
  12. Click Calculate
     
    Compound Interest
  13. Close the form
  14. When asked whether you want to save it, click Yes

Select...Case-Related Functions: Switch()

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:

Private Sub cmdFunction_Click()
    Dim Status As Integer, EmploymentStatus As String

    Status = 1
    EmploymentStatus = "Unknown"

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

    MsgBox "Employment Status: " & EmploymentStatus
End Sub

This would produce:

Switch

In this example, we used a number as argument. You can also use another type of value, such as an enumeration. 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.

For Each of the Next Items

 

For Counting Next

To assist you with counting the items of a list, the Visual Basic language provides the For...Next loop. The syntax used is:

For Counter = Start To End
  Statement(s)
Next

Used for counting, the For...Next loop begins counting at the Start point. Then it examines whether the current value (after starting to count) is greater than End; if that's the case, the program exits the loop. It then executes the Statement or Statements. Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until Counter = End.

The syntax above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the syntax you would use:

For Counter = Start To End Step Increment
  Statement(s)
Next Counter

You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. This means that you can give it a negative value, in which case the Counter would be subtracted the set value.

For...Each Item in a Collection

Since the For...Next loop is used to execute a group of statements based on the current result of the loop counting from Start to End, an alternative is to state various steps in the loop and execute a group of statements for each one of the elements in the group. This is mostly used when dealing with a collection of items.

The syntax of a For...Each statement is:

For Each Element In Group
    Statement(s)
Next Element

The loop will execute the Statement or Statement(s) for each Element in the Group.

Looping

 

Do While...Loop

Loops are used to repeat an action and they use the Do keyword in combination with other keywords to perform and conditional statement. There are various variations of the Do loops.

The syntax of the Do While loop is:

Do While Condition
    Statement(s)
Loop

The program will first test the Condition. If the Condition is true, the program would execute the Statement or Statements and go back to the Do While statement and test the condition again. This expression will execute the Statement or statements AS LONG AS the Condition is true, as many times as the Condition will be visited and found true. If the Condition is false, the program will skip the Do While statement and not execute any.

Here is an example:

Private Sub cmdCounter_Click()
    Dim Number As Integer
        
    Do While Number < 46
        MsgBox CStr(Number)
        Number = Number + 4
    Loop

    MsgBox "Counting Stopped at " & CStr(Number)
End Sub

Do...Loop While

Since the Do While statement tests the Condition first before executing the Statement, sometimes you will want the program to execute the Statement first, then go back and test the Condition. Visual Basic offers a reverse to the syntax, which is:

Do
  Statement(s)
Loop While Condition

In this case, Visual Basic will execute the Statement or Statements first, then it will test the Condition. If the Condition is true, the program will execute the Statement again. The program will continue this examination-execution as long as the Condition is true. The big difference here is that even if the Condition is false, the program will have executed the Condition at least once.

Here is an example:

Private Sub cmdCounter_Click()
    Dim Answer As String

    Do
        Answer = CStr(InputBox("Are we there yet (1=Yes/0=No)?", "Counter", "1"))
    Loop While Answer <> "1"

    MsgBox "Wonderful, we have arrived"
End Sub

Here is an example of running the code:

Do Until...Loop

An alternative to the Do While loop is the Do Until loop. Its syntax is:

Do Until Condition
    Statement(s)
Loop

This loop will first examine the Condition, instead of examining whether the Condition is true, it will test whether the Condition is false.

Here is an example:

Private Sub cmdCounter_Click()
    Dim Answer As String

    Do Until (Answer = "1")
        Answer = InputBox("Are we there yet (1=Yes/0=No)?", "Counter", "1")
    Loop

    MsgBox "Wonderful, we have arrived"
End Sub

Do...Loop Until

The other side of the Do Until loop would execute the Statement first, then it would examine the Condition. The syntax used is:

Do
    Statement(s)
Loop Until Condition
 
 
   
 

Previous Copyright © 2002-2015, FunctionX, Inc. Next