Case Function Equivalent in Excel

前端 未结 12 844
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 18:29

I have an interesting challenge - I need to run a check on the following data in Excel:

|   A  -   B  -   C  -  D   |
|------|------|------|------|
|  36  |          


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 19:05

    If you don't have a SWITCH statement in your Excel version (pre-Excel-2016), here's a VBA implementation for it:

    Public Function SWITCH(ParamArray args() As Variant) As Variant
        Dim i As Integer
        Dim val As Variant
        Dim tmp As Variant
    
        If ((UBound(args) - LBound(args)) = 0) Or (((UBound(args) - LBound(args)) Mod 2 = 0)) Then
            Error 450       'Invalid arguments
        Else
            val = args(LBound(args))
            i = LBound(args) + 1
            tmp = args(UBound(args))
    
            While (i < UBound(args))
                If val = args(i) Then
                    tmp = args(i + 1)
                End If
                i = i + 2
            Wend
        End If
    
        SWITCH = tmp
    End Function
    

    It works exactly like expected, a drop-in replacement for example for Google Spreadsheet's SWITCH function.

    Syntax:

    =SWITCH(selector; [keyN; valueN;] ...  defaultvalue)
    

    where

    • selector is any expression that is compared to keys
    • key1, key2, ... are expressions that are compared to the selector
    • value1, value2, ... are values that are selected if the selector equals to the corresponding key (only)
    • defaultvalue is used if no key matches the selector

    Examples:

    =SWITCH("a";"?")                       returns "?"
    =SWITCH("a";"a";"1";"?")               returns "1"
    =SWITCH("x";"a";"1";"?")               returns "?"
    =SWITCH("b";"a";"1";"b";TRUE;"?")      returns TRUE
    =SWITCH(7;7;1;7;2;0)                   returns 2
    =SWITCH("a";"a";"1")                   returns #VALUE!
    

    To use it, open your Excel, go to Develpment tools tab, click Visual Basic, rightclick on ThisWorkbook, choose Insert, then Module, finally copy the code into the editor. You have to save as a macro-friendly Excel workbook (xlsm).

提交回复
热议问题