Excel VBA – If Then Statement in Excel

Excel VBA – If Then Statement: Use the If Then statement in Excel VBA to execute code lines if a specific condition is met. The IF Then Statement in Excel VBA is used to execute one set of code if a specified condition evaluates to TRUE, or another set of code if it evaluates to FALSE.

Use the If…Then…Else statement to run a specific statement or a block of statements, depending on the value of a condition. If…Then…Else statements can be nested to as many levels as you need.

However, for readability, you may want to use a Select Case statement rather than multiple levels of nested If…Then…Else statements.

If Then Statement

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

Dim score As Integer, result As String

score = Range(“A1”).Value

 

If score >= 60 Then result = “pass”

Range(“B1”).Value = result

Explanation: if score is greater than or equal to 60, Excel VBA returns pass.

Result when you click the command button on the sheet:

"Excel

Note: if score is less than 60, Excel VBA places the value of the empty variable result into cell B1.

Else Statement

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

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 score is greater than or equal to 60, Excel VBA returns pass, else Excel VBA returns fail.

- Advertisement -

Result when you click the command button on the sheet:

"Excel

Note: only if you have 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 (first example). Otherwise start a new line after the words Then and Else and end with End If (second example).

The Microsoft Excel If…Then…Else statements can only be used in VBA code. It executes one set of code if a specified condition evaluates to TRUE, or another set of code if it evaluates to FALSE.

The If…Then…Else statements is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

 

Next Chapter: Loop
See also  Excel VBA - Macro Errors in Excel

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Stay in touch to boost your skills in Excel, HTML, and JavaScript! Get tips, tutorials, and practical examples to make your learning journey efficient, fun, and highly rewarding.

Related Articles