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:
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” Range(“B1”).Value = result |
Explanation: if score is greater than or equal to 60, Excel VBA returns pass, else Excel VBA returns fail.
Result when you click the command button on the sheet:
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 |