本文介绍了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.

推荐答案

从code,函数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

......终于,一些测试code行使的功能:

...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

需要注意的是实现该接口的类必须有一个名为&LT方法;接口> _<方法> 在上面的例子中,不只是&LT ;方法> 如你所期望

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.

下载href=\"https://dl.dropbox.com/u/6194904/2012/demo%20functions%20as%20arguments%20of%20functions.xlsm\" rel=\"nofollow\">简单的演示<或这里中间演示

Download the simple demo or intermediate demo here

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

08-14 22:57