ilearnexcelvba

iLearn Excel VBA: If-Then-Else

By Peter Atoria  //  August 27th, 2011  //  Visual Basic  //  No Comments

The Almighty If-Then-Else

The If-Then-Else is a perfect example of a conditional statement. A conditional statement is a true/false statement that is computed to determine if a code segment should be executed. Let’s have a look at a practical example:

Sub TheIfStatement()
    Dim i As Integer
    i = 100
    If (i = 100) Then
        Debug.Print "i equals 100"
    End If
End Sub

If you copy and paste the above sub routine into a module you will see i equals 100 displayed in your immediate window. We can see in lines 2 and 3 that i is an integer that equals 100. Line 4 asks if variable i equals 100 then execute the following code. Now that we understand how conditionals work, let’s expand the If-Then-Else statement to it’s full potential:

Sub TheIfStatement()
    Dim i As Integer
    i = 100
    If (i = 100) Then
        Debug.Print "i equals 100"
    ElseIf (i = 0) Then
        Debug.Print "i equals 0"
    Else
        Debug.Print "i equals something else"
    End If
End Sub

It is basically the same module with a little addition. Line 4 remains the same, but now line 6 asks, alright if i does not equal 100 and i equals 0 then execute the following code. Also, newly added is line 8 where it asks, alright if i does not equal 100 or 0 then execute the following code. This is the easiest and most used statement in most Visual Basic scripts. Note here that I only have 1 ElseIf in my If-Then-Else, but you can as many as you want. Next time let’s chat about a For-Loop and what it does, signing off ~iAtoria.

ABOUT THE GUY WHO WROTE THIS

Leave a comment