Case Function Equivalent in Excel

前端 未结 12 938
被撕碎了的回忆
被撕碎了的回忆 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:14

    Recently I unfortunately had to work with Excel 2010 again for a while and I missed the SWITCH function a lot. I came up with the following to try to minimize my pain:

    =CHOOSE(SUM((A1={"a";"b";"c"})*ROW(INDIRECT(1&":"&3))),1,2,3)
    CTRL+SHIFT+ENTER
    

    where A1 is where your condition lies (it could be a formula, whatever). The good thing is that we just have to provide the condition once (just like SWITCH) and the cases (in this example: a,b,c) and results (in this example: 1,2,3) are ordered, which makes it easy to reason about.

    Here is how it works:

    • Cond={"c1";"c2";...;"cn"} returns a N-vector of TRUE or FALSE (with behaves like 1s and 0s)
    • ROW(INDIRECT(1&":"&n)) returns a N-vector of ordered numbers: 1;2;3;...;n
    • The multiplication of both vectors will return lots of zeros and a number (position) where the condition was matched
    • SUM just transforms this vector with zeros and a position into just a single number, which CHOOSE then can use
    • If you want to add another condition, just remember to increment the last number inside INDIRECT
    • If you want an ELSE case, just wrap it inside an IFERROR formula
    • The formula will not behave properly if you provide the same condition more than once, but I guess nobody would want to do that anyway

提交回复
热议问题