在VBA中定义一个函数别名,可能吗?

时间:2010-11-30 10:04:06

标签: vba function-pointers alias

我在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 个答案:

答案 0 :(得分:6)

会跑步吗?

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

答案 1 :(得分:3)

如果2个功能在2个不同的类模块中实现,你可以给它们相同的名称&通过界面调用它们。那就是你能得到的尽可能接近。 (而且不是非常接近)

'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

答案 2 :(得分:1)

不,不幸的是,这对VBA来说是不可能的。会很好,但你必须坚持你的第一个语法。

更新:所以,我坚持我最初的断言,即问题中提出的构造在VBA中不存在,但Alex K.Remou提供了可用的解决方法。

答案 3 :(得分:1)

试试这个:

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支持它中途。是的,你可以得到一个函数的地址,但你不能调用按地址函数(除非该函数是一个消息处理器,然后才使用Win32函数CallWndProc)。模拟这种行为所能做的只是采用通用调度对象而不是函数指针,并确保对象支持必要的函数。“ / p>

不幸的是,我相信你的情况会尽可能接近。

有关AddressOf的详情,请参阅here

答案 4 :(得分:0)

我意识到这是一个老问题,但是我建议使用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
相关问题