Return to VBA Code Examples

VBA Switch Statement

This article will demonstrate how to use the VBA Switch statement.

The VBA Switch statement is used in a similar way to the VBA Select Case statement.

The Syntax of the Switch Statement

The switch statement evaluates a list of expressions to see if they are true or false, and returns the value of the first expressions that is evaluated as true.   The argument list is made up of pairs – an expression and a value that is returned if the expression is evaluated as being true.

Switch(expr-1value-1, [ expr-2value-2…, [ expr-nvalue-n ]])

Using the Switch statement in a VBA Procedure

To use this in a macro could be similar to this example below:

Sub TestSwitch()
   Dim strCompany As String
   Dim CompanyID As Integer
   CompanyID = 2
   strCompany = Switch(CompanyID = 1, "Apple", CompanyID = 2, "IBM", CompanyID = 3, "Samsung")
   MsgBox strCompanies
End Sub

We are declaring a integer variable to hold the values from the expressions within the switch statement. We then declare another string variable to return the value that is contained within that expression.

Using the Switch Statement with a Range

Instead of hard-coding the value that the switch is going to evaluate into the code, we can use a value that we have stored in an Excel cell to return the string the we require.

Sub TestSwitch()
  Dim strCompany As String 
  Dim CompanyID As Integer
  CompanyID = Range("A2")
  strCompany = Switch(CompanyID = 1, "Apple", CompanyID = 2, "IBM", CompanyID = 3, "Samsung")
  MsgBox strCompanies
End Sub

To use this procedure, we would need to have a number in the cell A2 in the worksheet.  We can then run the macro to get the name of the company (ie Samsung).

VBA Switch Range

If we do not have a number in cell A3 and we run the code, a Type Mismatch Error will be returned.

VBA Switch Error

Creating a Custom Function with VBA Switch

We can also create a custom function using VBA switch and use it within our Workbook.

Function SwitchStatement(i As Integer) As String
  SwitchStatement = Switch(i= 1, "Apple", i= 2, "IBM", i= 3, "Samsung")
End Function

To use this within our workbook, we can use the Insert Function dialog box.

Click in the cell A3 and then click on Insert Function in the Function bar.

VBA Switch InsertFunction

From the Insert Function dialog box, select User Defined from the Select Category drop down list, and then select SwitchStatement.

VBA Switch SelectFunction

Click OK, and then click on cell A2.

VBA Switch FunctionResult

The name of the company, as stored in the Switch Statement will be returned to our worksheet.

VBA Switch ExcelResult

 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!