代码之家  ›  专栏  ›  技术社区  ›  orshachar

可以在VBA中定义函数别名吗?

  •  5
  • orshachar  · 技术社区  · 14 年前

    我在MS Access后面使用VBA 假设我有全局方法foo1和foo2,它们得到相同的参数,但是做不同的事情。 我知道,在C++中,我可以给函数赋值别名。类似于: 而不是:

    If (term) then
       foo1 arg1, arg2, arg3
    else
       foo2 arg1, arg2, arg3
    End If
    

    我想写:

    Var new_func = Iff (term, foo1,foo2)
    new_func arg1, arg2, arg3
    

    我可以在vba上做这个吗?

    5 回复  |  直到 14 年前
        1
  •  7
  •   Fionnuala    14 年前

    会穿西装吗?

    new_func = IIf(term, "foo1", "foo2")
    ''new_func arg1, arg2, arg3
    
    res = Run(new_func, "a", "b", 1)
    

    更多信息: http://msdn.microsoft.com/en-us/library/aa199108(office.10).aspx

        2
  •  4
  •   C. Ross trotttrotttrott    11 年前

    如果这两个函数是在两个不同的类模块中实现的,则可以为它们指定相同的名称,并通过接口调用它们。那是最接近的了。(而且不太接近)

    'empty interface class, name: IFoo
    Public Function TheFunc(i As Integer) As Long
    '
    End Function
    
    'class clsFoo1
    Implements IFoo
    
    Private Function IFoo_TheFunc(i As Integer) As Long
    MsgBox "I'm clsFoo1"
    End Function
    
    'class clsFoo2
    Implements IFoo
    
    Private Function IFoo_TheFunc(i As Integer) As Long
    MsgBox "I'm clsFoo2"
    End Function
    
    'module code;
    Dim myFoo As IFoo
    If var = 1 Then
        Set myFoo = New clsFoo1
    Else
        Set myFoo = New clsFoo2
    End If
    
    myFoo.TheFunc 12345
    
        3
  •  1
  •   Mark Mayo    14 年前

    试试这个:

    http://oreilly.com/catalog/vbanut/chapter/booklet.html#sect5

    这个 AddressOf 接线员。

    但如前所述 http://discuss.fogcreek.com/joelonsoftware4/default.asp?cmd=show&ixPost=140196&ixReplies=19

    “AddressOf真是个廉价的黑客。VB不像大多数其他语言那样支持一级函数值,但是使用AddressOf is则支持一半。是的,您可以获取函数的地址,但不能逐地址调用函数(除非该函数是消息处理器,然后才使用Win32函数CallWndProc)。要模拟此行为,您所能做的就是采用通用分派对象而不是函数指针,并确保这些对象支持必要的函数。”

    不幸的是,我相信这是最接近你的了。

    有关的详细信息 地址 ,请参见 here .

        4
  •  1
  •   Community CDub    7 年前

    不,不幸的是,VBA不可能做到这一点。很好,但你只需要坚持你的第一个语法。

    更新:所以,我站在我原来的主张,在这个问题中提出的结构不存在于VBA,但 Alex K. Remou 提供了可用的解决方法。

        5
  •  0
  •   Sancarn    6 年前

    我知道这是个老问题,但我建议 STD.Types.Callback 它是我的VBA库的一部分。

    用法:

    sub test()
      Dim msg as STD_Types_Callback
      set msg = STD.Types.Callback.Create("Module","Module1","Msg")
      'or
      'set msg = STD.Types.Callback.Create("Object",myObject,"Msg")
    
      DoMessage(msg, "hello world") '=> "hello world"
    end sub
    
    
    function Msg(message)
      Msgbox message
    end function
    
    function DoMessage(a as object, b as string)
      a(b)
    end function