我想为 excel 创建“案例”公式来模拟选择案例行为(带有多个参数,否则是可选的)。如果 A1 和 A2 是 excel 单元格,那么目标是:
A1 Case: A2 Formula: A2 Result
5 cases({A1>5,"greather than 5"}, {A1<5, "less than 5"},{else,"equal to 5"}) equal to 5
Hi cases({A1="","there is nothing"},{else,A1}) Hi
1024 cases({5<A1<=10,10},{11<=A1<100,100},{A1>100,1000}) 1000
12 cases({A1=1 to 9, "digit"}, {A1=11|22|33|44|55|66|77|88|99, "11 multiple"}) (empty)
60 cases({A1=1 to 49|51 to 99,"not 50"}) not 50
如果可以,它必须接受 excel 公式或 vba 代码,以便在处理案例之前对单元格进行操作,ig
cases({len(A1)<7, "too short"},{else,"good length"})
如果可以,它必须接受一个或多个单元格来评估,ig
如果 A2=A3=A4=A5=1 和 A1=2,A6="一个",A7="两个"
cases(A1!=A2|A3|A4|A5, A6}, {else,A7}) will produce "two"
顺便说一句,| 表示或,!= 表示不同
有什么帮助吗?
我很感激。
我能写的是这样的:
Public Function arr(ParamArray args()) 'Your function, thanks
arr = args
End Function
Public Function cases(arg, arg2) 'I don't know how to do it better
With Application.WorksheetFunction
cases = .Choose(.Match(True, arg, 0), arg2)
End With
End Function
我以这种方式调用函数
=cases(arr(A1>5, A1<5, A1=5),arr( "gt 5", "lt 5", "eq 5"))
而且我无法达到目标,它只适用于第一个条件,A1>5。
我使用 for 修复了它,但我认为它不像您的建议那样优雅:
Function selectCases(cases, actions)
For i = 1 To UBound(cases)
If cases(i) = True Then
selectCases = actions(i)
Exit Function
End If
Next
End Function
当我调用函数时:
=selectCases(arr(A1>5, A1<5, A1=5),arr( "gt 5", "lt 5", "eq 5"))
有用。
谢谢大家。
经过一番工作,最后我得到了一个 excel 选择案例,更接近我最初想要的。
Function cases(ParamArray casesList())
'Check all arguments in list by pairs (case, action),
'case is 2n element
'action is 2n+1 element
'if 2n element is not a test or case, then it's like the "otherwise action"
For i = 0 To UBound(casesList) Step 2
'if case checks
If casesList(i) = True Then
'then take action
cases = casesList(i + 1)
Exit Function
ElseIf casesList(i) <> False Then
'when the element is not a case (a boolean value),
'then take the element.
'It works like else sentence
cases = casesList(i)
Exit Function
End If
Next
End Function
当 A1=5 我打电话给:
=cases(A1>5, "gt 5",A1<5, "lt 5","eq 5")
可以这样读:当A1大于5时,则选择“gt 5”,而当A1小于5时,则选择“lt 5”,否则选择“eq 5”。运行后,它与“eq 5”匹配
谢谢,这很令人兴奋,而且很有教育意义!