VBA IF FUNCTION

IF

IF Function is most frequently used function in excel vba. This function checks that given condition is being met or not. If condition meet then which action will be taken or not make then which action will be taken. Action means what code will be executed. We can set multiple condition and multiple code with if function, but here I am going to explain one by one. Must remember if in excel vba is case sensitive, man A & a both are not same. In excel “A”=a” output will be True, But in excel vba “A”=”a” output will be false.


Example:-1

 

Cell A1 has a value 15. I have to make a macro if value is greater than 10 then a message box will be appeared with message “Value is Greater than 10”, for this we have to type below macro code. If condition will be fulfill then, Code after then will be executed.

Sub If_1()
If Range(“A1”).Value > 10 Then MsgBox “Value is greater than 10”
End Sub

After executing this code below message box will be appeared. Here only one code to execute. If we have multiple code to execute then we need to use other line code, if will be closed with end if.

 

 

 

 

 

 

 


Example :-2

In upper example we have typed if syntax in one line, If we break code after then, in this case we will have to use end if to close if. See below macro coding.

Sub If_2()
If Range(“A1”).Value > 10 Then
MsgBox “Value is greater than 10”
End If
End Sub


Example :-3

Cell A1 has a value 15. I have to make a macro if value is greater than 10 then a message box will be appeared with message “Value is Greater than 10” and if value is less than 10 then a message box will be appeared with message “Value is Less than 10”. For this we have to use Else, see below macro coding. If condition will be fulfill then, 1st code will be executed if condition will not be fulfill then Code after else will be executed.

Sub If_3()
If Range(“A1”).Value > 10 Then
MsgBox “Value Is Greater Than 10”
Else
MsgBox “Value Is Less Than 10”
End Sub


Example:-4

In above examples we have one or two condition, Now I am going to increase condition. Here is 4 conditions. For 1st I have used If, for 2nd if I have used Elseif, for 3rd if I have Elseif and for rest or Last condition I have used Else. If 1st if condition will be fulfill then, Code after then will be executed, if 2nd if condition, means 1st elseif condition will be fulfill then, code after that then will be executed, if 3rd if condition, means 2nd elseif condition will be fulfill then, code after that then will be executed, other wise code after else will be executed.

 

Sub If_4()
If Range(“A5”).Value = “A” Then
MsgBox “Apple”
ElseIf Range(“A5”).Value = “B” Then
MsgBox “BALL”
ElseIf Range(“A5”).Value = “C” Then
MsgBox “CAT”
Else
MsgBox “Other VAlue”

End If

End Sub

 

Download Example File