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

查看:268
本文介绍了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.

我要完成的是这样的:

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.

推荐答案

从你的代码中,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

请注意,实现接口的类必须有名为< Interface> _< Method> 如上例所示,不仅仅是< Method>

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天全站免登陆