Excel VBA: IF THEN Statement

VBA Excel: IF THEN Statement
This conditional statement enables you to check one condition and on the basis of that then run one or multiple statements if the condition holds. If the IF…THEN statement closes in the same line, the END IF is not required else IF…THEN statement should close with END IF.

Syntax

If <Condition> Then <Statement>

OR

If <Condition> Then 

Example 1: The below program checks if in ‘Sheet1’, we have UK mentioned or not in the cell A2 and if UK is present, it will return London

Sub IF_Condition_Example1()
  'checking the condition
  If Worksheets("Sheet1").Cells(2, 1).Value = "India" Then
  'will return Delhi in cell B2
  Worksheets("Sheet1").Cells(2, 2).Value = "Delhi"
  End If
 End Sub 

Output

IF THEN Statement in VBA1

Example 2: If the cell (C2) is greater than 4 lakh, then divide the value by 100 and return the value in B2 by using IF, THEN.

Sub IF_Condition_Example2()
  'Check if cell(C2) is greater than 400000
  If Range("A2") > 400000 Then
  'will return 8000 in cell B2
  Range("B2") = Range("A2") / 100
  End If
 End Sub 

Output

IF THEN Statement in VBA2