How to use If then else statement in Microsoft Excel VBA

Using If then Else statement can Execute specific condition that met given criteria.

Place a command button see this below example.

1.If statement.

Sub ifthenexample()
Dim number As Integer
Dim result As String
number = Range("a1").Value
If number >= 80 Then result = "Good"
Range("b1").Value = result
End Sub

Out put.


Explanation: if cells A1 value greater than 80 then VBA Return the result "Good".

Now its time to learn How to use if and else statement.

2.If Else statement.

Sub ifthenexample()
Dim number As Integer
If number > 80 Then
Range("b1").Value = "Good"
Else
Range("b1").Value = "Bad"
End If
End Sub


Out put.


Explanation:  if Value greater then 80 VBA out put Good else Bad.

Note: Using if statement Always End with End if code.

Ok Now let see How to use if else and elseif statement more than one condition.

Sub ifthenexample()
If Range("a1").Value = "admin" Then
Range("b1").Value = "Hi admin"
ElseIf Range("a1").Value = "Anonymous" Then
Range("b1").Value = "Please Register and continue"
End If
End Sub

Out put.



Explanation: If user name admin then VBA welcomes the user, Else if username Anonymous then VBA asks user to Register or login.




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 elseif end with End If (second example).

Please Refer this video for easy understanding






Do you like this page.? Please register your Email Id for News Letter..!!
How to use If then else statement in Microsoft Excel VBA How to use If then else statement in Microsoft Excel VBA Reviewed by Unknown on 09:45 Rating: 5

1 comment:

Powered by Blogger.