Write concise code with the Switch function

Many VB developers don’t realize that the Switch built-in function can often save a lot of code. This function takes any number of (expr, value) pairs, it evaluates all expressions and return the value related to the first expression that is found to be True. Typically you can use a Switch function to replace a If…ElseIf block, as in:

' the standard wayIf x = 0 Then    result = 100ElseIf x < y Then    result = xElseIf x > y Then    result = yElse    ' X = Y and X <> 0    result = 200End If' the more concise code' Note that the Else clause is rendered with a True constantresult = Switch(x = 0, 100, x < y, x, x > y, y, True, 200)

If no expressions in the list returns a non-zero value, the Switch function returns Null. If you want to avoid this, just use True for the last expression in the list, as in the above example.

It is important to note that the Switch function always evaluate all the arguments passed to it, so you get an error whenever any argument is invalid, for example:

' the following statement raises a "Division by Zero" error if Y=0MsgBox Switch(x = 0, "X is zero", y = 0, "Y is zero", True, "X/Y = " & x / y)

You can use the Switch function to quickly evaluate the minimum and the maximum of three values:

' the minimum of n1, n2, n3min = Switch(n1 <= n2 And n1 <= n3, n1, n2 <= n1 And n2 <= n3, n2, True, n3)' the maximum of n1, n2, n3max = Switch(n1 >= n2 And n1 >= n3, n1, n2 >= n1 And n2 >= n3, n2, True, n3)

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS