Last active
April 5, 2018 19:05
-
-
Save dashaw92/44e197a36a2d832148e7b6dcbe334280 to your computer and use it in GitHub Desktop.
Emulates the SWITCH function introduced in Excel 2016.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Author: Daniel Shaw (dashaw92) - April 1, 2018 | |
' This function emulates the behavior of SWITCH, | |
' a convenience function introduced in Excel 2016. | |
' | |
' To add this function to Excel, follow the steps listed on: | |
' https://support.office.com/en-us/article/create-custom-functions-in-excel-2f06c10b-3622-40d6-a1b2-b6748ae8231f | |
' | |
' Note: The 2016 version has a limit of 126 | |
' conditions and results, whereas this version is | |
' only limited by memory. Otherwise, this should be | |
' cross compatible with the 2016 version. | |
Function SWITCH(predicate, val1, res1, ParamArray tests()) | |
' Since val1 and res1 aren't optional, we can test these directly. | |
If predicate = val1 Then | |
SWITCH = res1 | |
Exit Function | |
ElseIf UBound(tests) < 0 Then | |
' The predicate isn't the same as val1, and we have no other arguments. | |
' Return False. | |
SWITCH = CVErr(xlErrNA) | |
Exit Function | |
End If | |
For i = 0 To UBound(tests) | |
' Param array must be the last parameter in the signature, | |
' so here is a hack to implement the default parameter. | |
' If the tests array has an odd amount of arguments, we | |
' assume that the last element in the array is the default | |
' parameter. Conditions and results come in pairs. | |
If i Mod 2 = 0 And i = UBound(tests) Then | |
SWITCH = tests(i) | |
Exit Function | |
End If | |
' Otherwise, we'll test the value at tests[i] and return | |
' tests[i + 1] if it's true. | |
If predicate = tests(i) Then | |
SWITCH = tests(i + 1) | |
Exit Function | |
End If | |
Next i | |
' None of the conditions passed, so return False. | |
SWITCH = CVErr(xlErrNA) | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It appears that when viewing workbooks created in Excel 2016 or later,
SWITCH
is replaced with_xlfn.SWITCH
. To solve this, search and replace for_xlfn.SWITCH
withSWITCH
.