VBA IF Statement - A Complete Guide
VBA IF Statement - A Complete Guide
The following code shows a simple example of using the VBA If statement
Else
Every time you use an If Then statement you must use a matching End If statement.
When the condition evaluates to true, all the lines between If Then and End If are processed.
[lines of code]
[lines of code]
[lines of code]
End If
To make your code more readable it is good practice to indent the lines between the If Then and End If statements.
To indent the code you can highlight the lines to indent and press the Tab key. Pressing Shift + Tab will Outdent the code
i.e. move it one tab to the left.
You can also use the icons from the Visual Basic Toolbar to indent/outdent the code
Select code and click icons to indent/outdent
If you look at any code examples on this website you will see that the code is indented.
Sub ReadMarks()
Dim i As Long
For i = 2 To 11
End If
Next
End Sub
Results
Bryan Snyder
Juanita Moody
Douglas Blair
Leah Frank
Monica Banks
Play around with this example and check the value or the > sign and see how the results change.
If Conditions
The piece of code between the If and the Then keywords is called the condition. A condition is a statement that evaluates
to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like
>,<,<>,>=,<=,=.
The following are examples of conditions
x=5 x is equal to 5
You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.
When equals is used in a condition it means “is the left side equal to the right side”.
The following table demonstrates how the equals sign is used in conditions and assignments
The last entry in the above table shows a statement with two equals. The first equals sign is the assignment and any
following equals signs are conditions.
This might seem confusing at first but think of it like this. Any statement that starts with a variable and an equals is in the
following format
[variable] [=] [evaluate this part]
So whatever is on the right of the equals sign is evaluated and the result is placed in the variable. Taking the last three
assignments again, you could look at them like this
[x] [=] [5]
[b] [=] [6 = 5]
[x] [=] [MyFunc(5,6)]
Using If ElseIf
The ElseIf statement allows you to choose from more than one option. In the following example we print for marks that
are in the Distinction or High Distinction range.
Sub UseElseIf()
Debug.Print "Destinction"
End If
End Sub
The important thing to understand is that order is important. The If condition is checked first.
If it is true then “High Distinction” is printed and the If statement ends.
If it is false then the code moves to the next ElseIf and checks it condition.
Let’s swap around the If and ElseIf from the last example. The code now look like this
Sub UseElseIfWrong()
Debug.Print "Destinction"
End If
End Sub
In this case we check for a value being over 75 first. We will never print “High Distinction” because if a value is over 85 is
will trigger the first if statement.
To avoid these kind of problems we should use two conditions. These help state exactly what you are looking for a remove
any confusion. The example below shows how to use these. We will look at more multiple conditions in the section below.
Debug.Print "Destinction"
End If
Let’s expand the original code. You can use as many ElseIf statements as you like. We will add some more to take into
account all our mark classifications.
Using If Else
The Else statement is used as a catch all. It basically means “if no conditions were true” or “everything else”. In the
previous code example, we didn’t include a print statement for a fail mark. We can add this using Else.
Sub UseElse()
Debug.Print "Destinction"
Debug.Print "Credit"
Debug.Print "Pass"
Else
Debug.Print "Fail"
End If
End Sub
Sub AddClass()
startRow = 2
sClass = "Destinction"
sClass = "Credit"
sClass = "Pass"
Else
sClass = "Fail"
End If
Next
End Sub
The results look like this with column E containing the classification of the marks
Results
Using If And/If Or
You can have more than one condition in an If Statement. The VBA keywords And and Or allow use of multiple
conditions.
These words work in a similar way to how you would use them in English.
Let’s look at our sample data again. We now want to print all the students that got over between 50 and 80 marks.
We use And to add an extra condition. The code is saying: if the mark is greater than or equal 50 and less than 75 then
print the student name.
Sub CheckMarkRange()
For i = 2 To 11
End If
Next
End Sub
Results
Douglas Blair
Leah Frank
Monica Banks
In our next example we want the students who did History or French. So in this case we are saying if the student did
History OR if the student did French.
Sub ReadMarksSubject()
For i = 2 To 11
End If
Next
End Sub
Results
Bryan Snyder
Bradford Patrick
Douglas Blair
Ken Oliver
Leah Frank
Rosalie Norman
Jackie Morgan
Using Multiple conditions like this is often a source of errors. The rule of thumb to remember is to keep them as simple as
possible.
Using If And
The AND works as follows
What you will notice is that AND is only true when all conditions are true
Using If Or
The OR keyword works as follows
What you will notice is that OR is only false when all the conditions are false.
Mixing AND and OR together can make the code difficult to read and lead to errors. Using parenthesis can make the
conditions clearer.
Sub OrWithAnd()
subject = "History"
marks = 5
Debug.Print "True"
Else
Debug.Print "False"
End If
End Sub
Using If Not
There is also a NOT operator. This returns the opposite result of the condition.
Condition Result
TRUE FALSE
FALSE TRUE
as are
If True Then
If Not False Then
and
If False Then
A common usage of Not when checking if an object has been set. Take a worksheet for example. Here we declare the
worksheet
We want to check mySheet is valid before we use it. We can check if it is nothing.
There is no way to check if it is something as there is many different ways it could be something. Therefore we
use Not with Nothing
If you find this a bit confusing you can use parenthesis like this
Sub CheckVal()
val = 11
Debug.Print result
val = 5
Debug.Print result
End Sub
In our next example we want to print out Pass or Fail beside each student depending on their marks. In the first piece of
code we will use the normal VBA If statement to do this.
Sub CheckMarkRange()
For i = 2 To 11
End If
Next
End Sub
In the next piece of code we will use the IIf function. You can see that the code is much neater here.
Sub CheckMarkRange()
For i = 2 To 11
Next
End Sub
You can see the IIf function is very useful for simple cases where you are dealing with two possible options.
Sub CheckResultType2()
Dim i As Long, marks As Long
For i = 2 To 11
Else
End If
Next
End Sub
Sub UsingNestedIIF()
For i = 2 To 11
Next
End Sub
Using nested IIf is fine in simple cases like this. The code is simple to read and therefore not likely to have errors.
marks = 0
However, when marks is zero the code will give a “Divide by zero” error. This is because it evaluates both the True and
False statements. The False statement here i.e. (60 / Marks) evaluates to an error because marks is zero.
If we use a normal IF statement it will only run the appropriate line.
marks = 0
If marks = 0 Then
total = 0
Else
total = 60 / marks
End If
What this also means is that if you have Functions for True and False then both will be executed. So IIF will run both
Functions even though it only uses one return value. For example
Case [condition 1]
Case [condition 2]
Case [condition n]
Case Else
End Select
Let’s take our AddClass example from above and rewrite it using a Select Case statement.
Sub AddClass()
startRow = 2
sClass = "Destinction"
sClass = "Credit"
sClass = "Pass"
Else
sClass = "Fail"
End If
Next
End Sub
The following is the same code using a Select Case statement. The main thing you will notice is that we use “Case 85 to
100” rather than “marks >=85 And marks <=100”.
Sub AddClassWithSelect()
firstRow = 2
Case 85 To 100
Case 75 To 84
sClass = "Destinction"
Case 55 To 74
sClass = "Credit"
Case 40 To 54
sClass = "Pass"
Case Else
sClass = "Fail"
End Select
Next
End Sub
Using Case Is
You could rewrite the select statement in the same format as the original ElseIf. You can use Is with Case.
Case Is >= 85
Case Is >= 75
sClass = "Destinction"
Case Is >= 55
sClass = "Credit"
Case Is >= 40
sClass = "Pass"
Case Else
sClass = "Fail"
End Select
You can use Is to check for multiple values. In the following code we are checking if marks equals 5, 7 or 9.
Sub TestMultiValues()
marks = 7
Case Is = 5, 7, 9
Debug.Print True
Case Else
Debug.Print False
End Select
End Sub
If cell G1 contains “French” then your result should look like this
Result of exercise
Answer to Exercise
The following code shows how to complete the above exercise. Note: There are many ways to complete this so don’t be
put off if your code is different.
Sub WriteSubjectResults()
subject = Range("G1")
Exit Sub
End If
firstRow = 2
Range("H:L").ClearContents
outRow = 1
Dim i As Long, marks As Long, rowSubject As String
End If
outRow = outRow + 1
End If
Next i
End Sub