Excel VBA If Then Statement

Conditional Statement: If Then Statement in Excel VBA

Use the If Then statement in Excel VBA to execute code lines if a specific condition is met.

If Then Statement

Insert a command button on worksheet and add the following lines of code:

Dim intMarks As Integer, strResult As String

intMarks = Range(“A1”).Value

If intMarks >= 70 Then strResult = “Pass”

Range(“B1”).Value = strResult

Explanation: if score is greater than or equal to 70, MS Excel VBA will return Pass.

On clicking the Command button, the result will be displayed in Cell B1

displayed in Cell B1

Note: if score is less than 70, VBA will place an empty value of the variable into cell B1.

Else Statement

Further to previous tutorial of conditional statement, if you desire to cater the FALSE return of the statement, you need to use ELSE with IF statement. To get a better understanding of ELSE, follow the lines of code below:

Dim intMarks As Integer, strResult As String

intMarks = Range(“A1”).Value

If intMarks >= 70 Then

    strResult = “Pass”


    strResult = “Fail”

End If

Range(“B1”).Value = strResult

Explanation: if Marks are greater than or equal to 70 then MS Excel VBA will return pass otherwise it will return fail.

On clicking the Command button, the result will be displayed in Cell B1


Note: If your code has only one line after Then and no Else statement is required, it is allowed to place the full code in single line, however, if there are multiple lines of code as well as there is an Else statement as well, you will require to write your code from the next line after Then. Similarly, you will right the else case in a new line after Else keyword. Finally, you will place a closing EndIf keyword that will instruct the program to close the If statement.