ilearnexcelvba

iLearn Excel VBA: Select-Case

By Peter Atoria  //  December 14th, 2011  //  Excel, Visual Basic  //  No Comments

The Forgotten Select-Case

The Select-Case is often ignored when programming as it can be easily substituted with If-Then-Else statements. It functions much like a If-Then-Else statement and computes a conditional where if true, completes a segment of code. Let’s look at the example:

Sub SelectCaseStatment()
    Dim i As Integer
    i = 79
    Select Case i
        Case 0 To 59
            Debug.Print "Grade: F"
        Case 60 To 69
            Debug.Print "Grade: D"
        Case 70 To 79
            Debug.Print "Grade: C"
        Case 80 To 89
            Debug.Print "Grade: B"
        Case 90 To 100
            Debug.Print "Grade: A"
        Case Else
            Debug.Print "You need to enter a value between 0 and 100"
    End Select
End Sub

The output you will see in your Immediate Window will be Grade: C. In lines 2-3 we declare i to be an integer with a value of 79. Line 4 enters the Select-Case statement. It then proceeds to ask in line 5 “in the case that i is in between 0 and 59 inclusive (0 <= i <= 59), complete the statement below." We can clearly see that the case that our integer will follow is the case in line 9. The Select-Case is pretty simple to understand and I won’t delve too deeply into it, but it may be useful to you in the future. We are now finished with all the basics of Excel VBA, next time we will finally begin manipulating Cells & Ranges, signing off ~iAtoria.

ABOUT THE GUY WHO WROTE THIS

Leave a comment