The Python match case statement was introduced in Python 3.10. It provides similar functionality to the VBA Select Case statement, but also has additional features. For detailed background with examples see:
geekforgeeks – Python Match Case Statement
The example below illustrates the basic functionality using code called from Excel with pyxll.
@xl_func()
def SelectVal(n):
match n:
case 1:
return 'first odd'
case 2:
return 'first even'
case 3 | 5 | 7:
return 'odd'
case 4 | 6 | 8:
return 'even'
case _ if 8 < n < 12:
return 'between 9 and 11'
case _ :
return 'more than 11'
The code shows options for:
- Matching a single value (1 or 2)
- Matching 2 or more values with the or operator, e.g. 3 | 5 | 7:
- Matching any other value in a specified range using _ if condition :
- Matching any other value with _:
Calling from excel the results are:
