VBA – Decisions

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

 

Example:  To check whether the number entered by the user is negative or not.

Sub check_Num()

Dim num As Integer

num = InputBox(“Enter the number: “)

If number < 0 Then

MsgBox “Entered number is negative”

Else

MsgBox “Entered number is positive”

End If

End Sub

So first we are accepting number from the user. And then we check whether that number is greater than zero or not. If the number is less than zero, then IF block is executed and Saying “Entered Number is negative”. But however, if the number is greater than zero then the program jumps to the Else block and saying, “Entered number is positive”.

 

Example: To compare two numbers

Sub mySub()

Dim x,y As Integer

x = 80

y = 120

If x > y Then

MsgBox “X is Greater than Y”

Else

Msgbox “Y is Greater than X”

End If

End Sub

 

VBA – If-Else elseif Statement

Let’s make the same program while we have two or three condition as given

 

Sub mySub()

Dim x, y As Integer

x = 80

y = 80

If x > y Then

MsgBox “X is Greater than Y”

ElseIf y > x Then

Msgbox “Y is Greater than X”

Else

Msgbox “Both are EQUAL”

End If

End Sub

Enjoy the tutorial? Please spread the word :)

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