VBA – Decisions

The IF function sometime also called as IF THEN ELSE Statement in VBA is one of the most popular used of all statements. The IF function checks if the specified condition is being met or not.

It check if the condition evaluates to TRUE or FALSE.

So Here is a simple program to understand the if else concepts in VBA

Sub MyTest()

dim x as Integer

x=30

If x > 50 Then

MsgBox “Value is greater than 50”

else

MsgBox “Value is less than 50”

End If

End Sub

So here you have declared a variable called X, contain numeric value 30.

You have a condition if the value of X is greater than 50 then it should say “Value is greater than 50” otherwise it should say “Value is less than 50”. As we can see the current value is less than 50 and the output will be “Value is less than 50”.

Note: Although, it is not mandatory to have an Else Block with every IF statement. In such a case, if the condition inside IF statement evaluates to FALSE then the program control just moves to the next instruction (the instruction after the IF Block) and starts executing them sequentially.

Example:  to check whether the cell number is greater than five thousand

Sub Test()

If Range(“B2”) > 5000 Then

Range(“C2”) = Range(“B2”) * 5 / 100

Else

Range(“C2”) = Range(“B2”) * 10 / 100

End If

End Sub

Example: To check a number is Even or Odd

Sub Test()

dim num as Integer

num =InputBox(“Enter a Number”)

if num MOD 2 = 0 then

MsgBox “Number is Even”

else

MsgBox “Number is Odd”

End Sub

VBA For Excel Hirdesh Bhardwaj
VBA For Excel – 1st Edition

Leave a Reply

Your email address will not be published.

Enjoy the tutorial? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+2k
Google+
http://hirdeshbhardwaj.com/2017/04/04/vba-decisions/
YouTube31
YouTube