totn Access Functions

MS Access: Switch Function

This MSAccess tutorial explains how to use the Access Switch function with syntax and examples.

Description

The Microsoft Access Switch function evaluates a list of expressions and returns the corresponding value for the first expression in the list that is TRUE.

Syntax

The syntax for the Switch function in MS Access is:

Switch ( expression1, value1, expression2, value2, ... expression_n, value_n )

Parameters or Arguments

expression1, expression2, ... expression_n
List of expressions that are evaluated. The Switch function is looking for the first expression that evaluates to TRUE.
value1, value2, ... value_n
List of values. The Switch function will return the value associated with the first expression that evaluates to TRUE.

Returns

The Switch function returns any datatype such as a string, numeric, date, etc.

Applies To

The Switch function can be used in the following versions of Microsoft Access:

  • Access 2019, Access 2016, Access 2013, Access 2010, Access 2007, Access 2003, Access XP, Access 2000

Example

Let's look at how to use the Switch function in MS Access:

Switch (SupplierID=1, "IBM", SupplierID=2, "HP", SupplierID=3, "Nvidia")

In this example, if the SupplierID field is 1, then the Switch function will return "IBM".
If the SupplierID field is 2, then the Switch function will return "HP".
If the SupplierID field is 3, then the Switch function will return "Nvidia".

Example in VBA Code

The Switch function can be used in VBA code in Microsoft Access.

For example:

Dim LValue As String

LValue = Switch (SupplierID=1, "IBM", SupplierID=2, "HP", SupplierID=3, "Nvidia")

Example in SQL/Queries

You can also use the Switch function in a query in Microsoft Access.

For example:

Microsoft Access

In this query, we have used the Switch function as follows:

Expr1: Switch([SupplierID]=1,"IBM",[SupplierID]=2,"HP",[SupplierID]=3,"NVidia")

This query will return the following:

  • If the SupplierID field is 1, then the Switch function will return "IBM".
  • If the SupplierID field is 2, then the Switch function will return "HP".
  • If the SupplierID field is 3, then the Switch function will return "Nvidia".

The result will be displayed in a column called Expr1. You can replace Expr1 with a column name that is more meaningful.

For example:

SupplierName: Switch([SupplierID]=1,"IBM",[SupplierID]=2,"HP",[SupplierID]=3,"NVidia")

The results would now be displayed in a column called SupplierName.