Advertisement

If Then Statement vba special

If Then Statement

If Then Statement | Else Statement

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

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 VBA If Then Statement

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.

Result when you click the command button on the sheet:

Excel VBA Else Statement

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)



Credit for the above article goes to excel-easy.com

If you have any query or want any help related to excel feel free to join our Telegram channel and message us..

Channel link :

https://t.me/msexcelmaster101

Post a Comment

2 Comments