vba - 有没有办法在VBA中将算术和逻辑运算符作为方法参数传递?

标签 vba excel enums logical-operators

遇到了一些希望将运算符作为函数或方法中的参数传递的场景。 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 ,它有能力接收操作符即使有人可以解释此函数中可能的后端工作

  1. 它如何将这些字符串转换为正确的运算符
  2. 这是一个 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/

相关文章:

vba - 为方程定义变量

excel - 索引匹配 : String in cell to mappings

excel - VBA从填充形状中删除图像

java - 强制 child 使用自己定义的枚举

excel - 如何在 VBA 中连接字符串?

vba - 加速 Excel 宏?

syntax - 有没有办法在 Kotlin 的数据类中嵌套枚举?

java - 指定抽象方法的参数必须是枚举

excel - 另存为 .xls 的 VBA 文件格式

excel - 将 MIN/MAX 应用到数组的 LET 函数的奇怪行为