excel vba:特殊类型 - 作为函数参数的函数 [英] excel vba: Special Types - Functions as Arguments of Functions

查看:28
本文介绍了excel vba:特殊类型 - 作为函数参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VBA 中的函数没有特殊类型.我很难看到如何在 Excel VBA 中将函数作为参数添加到函数中.

There is no special type for functions in VBA. It is hard for me to see how to add functions as arguments to functions in Excel VBA.

我想要完成的事情是这样的:

What I am trying to accomplish is something like this:

function f(g as function, x as string) as string
        f = g(x)
end function

目前,我有一组小函数,它们都在重复自己,但只调用一个特定的函数.

Currently, I have a group of little functions all repeating themselves but with one call to a specific function.

推荐答案

从您的代码中,函数 g 接受一个字符串参数并返回一个字符串.我建议您创建一个名为 IStringFunction 的类模块来充当所有函数都支持的接口的定义,因此:

From your code, function g takes a string parameter and returns a string. I suggest you create a class module called IStringFunction to act as the definition of an interface that all functions will support, thus:

类模块:IStringFunction

Public Function Evaluate(ByVal s As String) As String
End Function

然后,创建几个实现此接口的示例函数:

Then, create a couple of example functions implementing this interface:

类模块:HelloStringFunction

Implements IStringFunction

Public Function IStringFunction_Evaluate(ByVal s As String) As String
    IStringFunction_Evaluate = "hello " & s
End Function

类模块:GoodbyeStringFunction

Implements IStringFunction

Public Function IStringFunction_Evaluate(ByVal s As String) As String
    IStringFunction_Evaluate = "goodbye " & s
End Function

...最后,一些测试代码来练习这些功能:

...and finally, some test code to exercise the functions:

(标准)模块:测试

Sub Test()

    Dim oHello As New HelloStringFunction
    Dim oGoodbye As New GoodbyeStringFunction

    MsgBox Evaluate(oHello, "gary")
    MsgBox Evaluate(oGoodbye, "gary")

End Sub

Private Function Evaluate(ByVal f As IStringFunction, ByVal arg As String) As String
    Evaluate = f.Evaluate(arg)
End Function

请注意,实现接口的类必须具有名为 _ 的方法,如上例所示,而不仅仅是 期待.

Note that the class implementing the interface must have methods named <Interface>_<Method> as in the example above, not just <Method> as you'd expect.

下载简单演示中间演示在这里

这篇关于excel vba:特殊类型 - 作为函数参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆