Sponsored Link

Sponsored Link

Tuesday, March 31, 2009

VBA, IF then condition

IF THEN: IF Then is use to perform comparison two values. However, to perform the test for set of data you will have to use IF then with Do while or For Next loop.

Lets take a look at basic IF Then example with single condition.

Sub LoopIFThen1()
If ActiveCell.Value >= 18 Then
    MsgBox "You are Major"
Else
    MsgBox "You are Minor"
End If
End Sub

If the active cell has value more than or equal to 18 then message box will appear saying "you are 18" otherwise nothing will happen.

Now, we will use IF then to see alternate condition as well. Alternate condition is like what should code perform if active cell is less than 18.

Sub LoopIFThen2()
If ActiveCell.Value >= 18 Then
    MsgBox "You are Major"
Else
    MsgBox "You are Minor"
End If
End Sub

After trying to simple example we will move little complex example with multiple condition. Like if the active cell has age entered than in next cell it will tell you whether you are infant, minor, major or senior citizen.

Sub LoopIFThen3()
If ActiveCell.Value < 2 And ActiveCell.Value <> "" Then
    ActiveCell.Offset(0, 1) = "Infant"
ElseIf ActiveCell.Value > 2 And ActiveCell.Value < 18 And ActiveCell.Value <> "" Then
    ActiveCell.Offset(0, 1) = "Minor"
ElseIf ActiveCell.Value >= 18 And ActiveCell.Value <= 60 And ActiveCell.Value <> "" Then
    ActiveCell.Offset(0, 1) = "Major"
ElseIf ActiveCell.Value > 60 And ActiveCell.Value <= 100 And ActiveCell.Value <> "" Then
    ActiveCell.Offset(0, 1) = "SENIOR CITIZEN"
Else
    MsgBox "Please check Value"
End If
End Sub

In Above example, Activecell(0,1) refers to next column in right. In forthcoming post, we will use other loops like Do while, For Next loop along with IF Then. Also, you if you have problem trying this example then try downloading the file with example. Link for same is mentioned below

Download IF Then Example

Please post your comments about the post and subscribe via email to receive latest updates

We assure you knowledge, not SPAM!

0 comments:

Post a Comment