Conditions In Excel VBA



Conditions are one of the important aspect of programming. The result of their evaluation determines the flow of execution and control. Conditions  form the core of Branching and Looping concepts. 


Looping is process in which a set of statements are repeated number of times. Normally condition is (conditions are) evaluated either at the entry or exit of the loop. The result determines whether to repeat or to exit the loop. In branching, a decision is made to select a given execution path out of many available. The decision is made after execution of conditions. 


Like any other programming language, Excel-VBA too supports conditions. Statements such as if .. then .. else .. end if , if .. then .. elseif … end if, select case … case is .. case else .. end select etc are supported by Excel-VBA. 


Mathematical operators such as +,-,*,/ etc are used to perform mathematical expression. Condition operators such as >, <, =, <>, >=,<= etc play vital role in evaluating conditional expression. Logical operators AND, OR, NOT etc evaluate logical expressions.

Consider following data 

 

 

This one was a very basic 2-way branching statement. On execution following messages will be displayed one after the another.

 




Instead of if..else..end if , we will use if .. elseif … end if. The code will look as shown below. This is an example of n-way branching statement.

 
On execution following message will be displayed.

 

Instead of use if .. elseif … end if, we can also use select case statement to address a n-way branching problem. Replace the shaded piece of code with the following lines.

 


On execution, we get the same result as obtained after executing if..elseif…end if code. 

Case makes our code more readable. hence, for n-way branching (where n is quite large), preferably use case statement.