If Then Statement in Excel VBA

Use the If Then statement in Excel VBA to check a condition and execute code only when that condition is satisfied.

If Then Statement

On your worksheet, insert a command button and use the code provided below:

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

If score >= 60 Then result = "pass"

Range("B1").Value = result

Explanation: Excel VBA will return “Pass” when the score is greater than or equal to 60.

The result after you click the button:

If Then Statement in Excel

Note: Excel VBA checks the score. If it’s less than 60, it puts the result in cell B1.

Else Statement

Insert a command button in your Excel worksheet and use the code shown below:

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

If score >= 60 Then
      result = "pass"
Else
     result = "fail"
End If

Range("B1").Value = result

Explanation: If the score is 60 or more, Excel VBA shows “Pass”; otherwise, it shows “Fail” using an If statement.

The result after you click the button:

Note: If there is only one line of code after Then and no Else block, you may write the code right after Then and do not need to write End If. Otherwise, press Enter after writing “Then” and “Else”, and finish with “End If” (as shown in the second example).

1/9 Completed! Explore if-then statements ➝
Next Chapter: Loop