Excel VBA Choose Function

VBA Choose Function: The Choose function in VBA chooses function selects the corresponding value from a list of arguments depending as per the specified index.

Syntax

Choose (Index, [Choice-1], [Choice-2], ...)

Parameter

Index (required) – This parameter represents the index of the value that you want to return. It must be a positive integer value (greater than 0) and less than or equal to a number of specified choices.

Choose-1 (optional)…- This parameter represents a list of possible values to be returned.

Return

This function returns a value from the list of arguments depending upon the specified index. It returns Null if the index is less than or equal to 0 or is greater than the number of choices.

Example 1

Sub ChooseFunction_Example1()
 ' This function returns the given values from a list of names.
 Dim index As Integer
 Dim choice
 index = 2
 choice = Choose (index, "Java", "VBA", "C#", "Python")
 ' choice is now equal to "VBA".
 MsgBox ("Your favorite language is " + choice)
 End Sub 

Output

Your favorite language is VBA

VBA Choose Function

Example 2

Sub ChooseFunction_Example2()
 ' This function returns the given values from a list of names.
 Dim index As Integer
 Dim choice
 index = InputBox(" Name India's national flower 1.Lotus  2. Rose  3. Sunflower 4 Lily ")
 choice = Choose(index, "Lotus", "Rose", "Sunflower", "Lily")
 If choice = "Lotus" Then
     MsgBox ("Your answer is correct. You can move to next level!!")
 Else
     MsgBox ("Oops! you have entered a wrong answer")
 End If
 End Sub 

Output

VBA Choose Function
VBA Choose Function

Example 3

Sub ChooseFunction_Example3()
 ' This function returns the given values from a list of names.
 Dim index As Integer
 Dim choice
 'initializing index value with more than the specified choices
 index = 10
 choice = Choose(index, "Java", "VBA", "C#", "Python")
 ' choice will return an run time error.
 MsgBox ("Your favorite language is " + choice)
 End Sub 

Output

VBA Choose Function