SWITCH function

Here is one practical example to compare IF and SWITCH. Instead of theory, let’s jump into practice.

In reporting I have had a habit to abbreviate the months as P1, P2, P3 and so on meaning January, February, March and so on.

If the month is in B3, you can convert period and number codes into month with IF-function below.

=IF(B3=”P1″;”Jan”;IF(B3=”P2″;”Feb”;IF(B3=”P3″;”Mar”;IF(B3=”P4″;”Apr”;IF(B3=”P5″;”May”;IF(B3=”P6″;”Jun”;IF(B3=”P7″;”Jul”;IF(B3=”P8″;”Aug”;IF(B3=”P9″;”Sep”;IF(B3=”P10″;”Oct”;IF(B3=”P11″;”Nov”;IF(B3=”P12″;”Dec”))))))))))))

This works, but sentence is quite long and not so clear at first sight.

However, with SWITCH you can do  the same bit easier.

=SWITCH(B3;”P1″;”Jan”;”P2″;”Feb”;”P3″;”Mar”;”P4″;”Apr”;”P5″;”May”;”P6″;”Jun”;”P7″;”Jul”;”P8″;”Aug”;”P9″;”Sep”;”P10″;”Oct”;”P11″;”Nov”;”P12″;”Dec”)

SWITCH function is quite straightforward. First you need to define the cell where is the value. That is B3 in our case. Then you specify if the value is like P1, then which value the function should return, that is Jan. If the value is P2, then SWITCH returns Feb. Please, note that when B3 is once defined, we don’t have to repeat the cell address.

One benefit with SWITCH is that you don’t have to count parentheses.

It is easier to nest the SWITCH than IF above.

Say, you have month and year as P5/21 meaning May 2021. This should be changed to May/21. The SWITCH above is not enough.

First, we need to extract P5. The slash might be third or fourth digit. This we can do with IF-formula below.

=IF(FIND(“/”;I3)=3;(LEFT(I3;2));IF(FIND(“/”;I3)=4;(LEFT(I3;3))))

If slash is the third digit, then two first digits are selected. If slash is the fourth digit, then three first digits are selected. From P5/21, only P5 is returned.

The sentence in F3 is below.

=SWITCH(IF(FIND(“/”;E3)=3;(LEFT(E3;2));IF(FIND(“/”;E3)=4;(LEFT(E3;3))));”P1″;”Jan”;”P2″;”Feb”;”P3″;”Mar”;”P4″;”Apr”;”P5″;”May”;”P6″;”Jun”;”P7″;”Jul”;”P8″;”Aug”;”P9″;”Sep”;”P10″;”Oct”;”P11″;”Nov”;”P12″;”Dec”)&(RIGHT(E3;3))

Here we combine the IF which is taking the P5 from P5/21. Then SWITCH is switching P5 to May. Finally, three last digits in E3 are added at the end of F3.

Think if you still had IF instead of SWITCH, the sentence would be even more complex. With SWITCH the sentence is clearer to comprehend. SWITCH makes possible to build longer sentences easier than IF, that is my opinion.