遇到了一些希望将运算符
作为函数或方法中的参数
传递的场景。 According to this post Java doesn't have that ability, hence need to create an Enum
as the primary workaround 。
例如
Function doCalcs(ByRef AND as LogicalOperator, ByRef greater ArithmeticOperator)
尽管与 .Net、Java 相比,VBA 的库要少得多,但创建 Enum
得到了很好的支持。也许我不知道,所以如果 VBA 可能有运算符类型
或任何其他解决方法,我们可以传递运算符
,将其射入。(除了 >if else
/case
检查包含运算符参数的字符串.. =) )我要问的是 different from what's mentioned here .
- 问题是在减少代码、优化方面提出的。
例如如果你看CountIFS
,它有能力接收操作符
。 即使有人可以解释此函数中可能的后端工作,
- 它如何将这些字符串转换为正确的
运算符
? - 这是一个
Enum
结构还是比它更高效或更低效的结构?
这些问题的答案仍然可以接受。
最佳答案
使用类的方法:
定义接口(interface)类
操作
Public Function eval(operand1, operand2)
End Function
对于每个所需的运算符,定义一个实现。例如
OpMinus
Implements Op
Private Function Op_eval(operand1 As Variant, operand2 As Variant) As Variant
Op_eval = operand1 - operand2
End Function
OpPlus
Implements Op
Private Function Op_eval(operand1 As Variant, operand2 As Variant) As Variant
Op_eval = operand1 + operand2
End Function
现在模块中的一些测试例程:
Sub test()
Dim Minus As New OpMinus
Dim Plus As New OpPlus
Dim o, v1, v2
For Each o In Array(Minus, Plus)
For Each v1 In Array(1, 2, 3)
For Each v2 In Array(1, 2, 3)
operate o, v1, v2
Next
Debug.Print ""
Next
Debug.Print ""
Next
End Sub
Sub operate(ByVal operator As Op, operand1, operand2)
Debug.Print operator.eval(operand1, operand2),
End Sub
输出:
0 -1 -2
1 0 -1
2 1 0
2 3 4
3 4 5
4 5 6
请注意,您可能希望使用例如如果您知道要操作的类型,则在界面中使用 Double
而不是 Variant
。
关于vba - 有没有办法在VBA中将算术和逻辑运算符作为方法参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482524/