If Then Statement

 

If Then Statement    |   Else Statement

In many situations we only want Excel VBA to execute certain code lines when a specific condition is met. The If Then statement allows you to do this. Instead of multiple If Then statements, you can use Select Case.

If Then Statement

Place a command button on your worksheet and add the following code lines:

Dim score As Integer, grade As String
score = Range("A1").Value

If score >= 60 Then grade = "passed"

Range("B1").Value = grade

1. The first code line declares two variables. One variable of type Integer and one variable of type String.

2. Next, we initialize the variable score with the value of cell A1.

3. If score is higher or equal to 60, we assign the text 'passed' to the variable grade.

4. Finally, we place the value of the variable grade into cell B1.

Exit the Visual Basic Editor, enter a value into cell A1, and click on CommandButton1.

Result:

If Then Statement Result

Else Statement

If score is lower than 60, the previous code lines empty cell B1. We can use an Else statement to assign the text 'failed' to the variable grade if score is lower than 60.

Code:

Dim score As Integer, grade As String
score = Range("A1").Value

If score >= 60 Then
    grade = "passed"
Else
    grade = "failed"
End If

Range("B1").Value = grade


Result when you click the command button on the sheet:

If Then Else Statement Result

Note: It is good practice to always start a new line after the words Then and Else and to end with End If (see second example). Only if there is one code line after Then and no Else statement, it is allowed to place a code line directly after Then and to omit (leave out) End If (see first example).

Did you find this information helpful? Show your appreciation, vote for us.

Go to Top: If Then Statement    |    Go to Next Topic: Cells

Lean more about if then statements, Login to the right >>
100 easy to follow Excel VBA examples. Limited time-offer: $39.00 but only $29.00. Ends on 31 May.