4 Multi-branch conditional statement

VBA also supports the use of a multi-branch conditional statement. In this case, a conditional statement has multiple conditions. Consider the following example:

if (x = 1) then  
  z = 52  
elseif (x = 3) then  
  z = 27  
else  
  z = 10  
end if  
  

Nevermind the seemingly meaningless logic. The important part is that the conditions are tested from top to bottom. As soon as a condition evaluates to true, the matching then-block to that expression executes, and the conditional statement is completed.

The following code finds the maximum of three variables w, x and y, and puts it (the maximum) in variable z:

if (w >= x) and (w >= y) then  
  z = w  
elseif (x >= w) and (x >= y) then  
  z = x  
else  
  z = y  
end if  
  

Note that this code illustrates one potential confusion with a multi-branch conditional statement. What if all three variables (w, x and y) all have the same value? Which statement, then, gives z a value?

We have to remember that VBA (and all programming languages that support multi-branch conditional statements) evaluates conditions of a multi-branch conditional statement from top to bottom. This means that the VBA interpret evaluates the condition (w >= x) and (w >= y) first. In the case that all three variables have the same value, this condition is true. As a result, the matching then-block, z = w, executes.