Excel VBA: IF…..THEN …ELSE Statement
VBA : IF…..THEN …ELSE Statement: This function enables you to check one condition and, based on that, then run one of the two statement blocks present. If the ‘IF’ condition is TRUE, IF statement and condition will run, if it is FALSE, then the ‘ELSE’ block will come in the loop. This statement will always have a closing ‘END IF’ statement else, VBA will give an error.
Syntax
If <Condition1> Then <Statements1> , Else (Statement2> , End If
Example 1: The below program checks if in ‘Sheet1’, India is present or not – if it is, then it will return ‘Delhi’ else ‘Master cell is not India’
Sub If_Then_Else_Example1() 'will check whether the data is India If Worksheets("Sheet1").Cells(2, 1).Value = "India" Then Worksheets("Sheet1").Cells(2, 2).Value = "Delhi" 'If the above case is not true, it will come to Else condition. Else Worksheets("Sheet1").Cells(2, 2).Value = "Master cell is not India" End If End Sub
Output
Example 2: Write a macro, checking if the candidate has scored more that 61 percentile, he/she is passed else he/she is failed.
Sub If_Then_Else_Example2() 'Variable declaration Dim Marks As String 'Accepting the value by the user Percentile = InputBox("Enter the candidate's percentile", "Marks") If Percentile >= 61 Then 'Check if the Candidate's has been selected MsgBox "Candidate is been selected!" Else 'Check if the Candidate has failed MsgBox "Sorry! Better Luck next time. " End If End Sub
Output
Example 3: Writing a macro, checking whether the user-entered number is an even or odd number.
Sub If_Then_Else_Example3() 'Variable declaration Dim Number As Integer 'Accepting a value by the user Number = InputBox("Enter a Number:", "Number") If Number Mod 2 = 0 Then 'Checking if the number is even MsgBox "The given number is Even." Else 'Checking if the number is odd MsgBox "The given number is Odd." End If End Sub
Output