VBA中的功能没有特殊类型。我很难看到如何在Excel VBA中添加函数作为函数的参数。
我想要完成的是这样的事情:
function f(g as function, x as string) as string
f = g(x)
end function
目前,我有一组小函数都在重复自己,但只需要调用一个特定的函数。
答案 0 :(得分:18)
由于VBA的根源是交互式语言,因此它始终具有执行文本的能力:
function f(g as string, x as string) as string
f = application.run(g,x)
end function
MyStringA = f("functionA",string1)
MyStringB = f("functionB",string1)
编辑添加: 我认为在当前版本的Excel中,应用程序(Excel)只能“运行”您可以在电子表格单元格中显示的内容。这意味着功能,而不是子程序。要执行子例程,请将其包装在函数包装器中:
function functionA(x as string)
Call MySubA(x)
end function
答案 1 :(得分:16)
从你的代码中,函数g接受一个字符串参数并返回一个字符串。我建议你创建一个名为IStringFunction的类模块,作为所有函数都支持的接口的定义,因此:
课程模块:IStringFunction
Public Function Evaluate(ByVal s As String) As String
End Function
然后,创建一些实现此接口的示例函数:
类模块: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
...最后,一些测试代码来运用这些功能:
(标准)模块:测试
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>
。
答案 2 :(得分:0)
可以将函数作为参数传递,并获得您所追求的行为,但它有点hacky。这是通过利用类的默认属性
来实现的myFunction
Public Function sayHi(ByVal s As String) As String
sayHi = "Hi " & s
End Function
你应该看到文件中的某个地方,一行定义你的功能
Public Function sayHi(ByVal s As String) As String
在其下方添加第Attribute Value.VB_UserMemId = 0
行,以便现在看起来像这样:
Public Function sayHi(ByVal s As String) As String
Attribute Value.VB_UserMemId = 0
sayHi = "Hi " & s
End Function
您在此处所做的是将sayHi
标记为班级的default property。现在,您可以单独通过类对象调用该函数class(args)
,而不是class.function(args)
保存修改后的文件并将其导入您的VBA项目
Sub test()
Dim parameterFunction As Object 'this is what we'll be passing to our routine
Set parameterFunction = New myFunction 'create instance of the function object
MsgBox f(parameterFunction, "Greedo")
End Sub
Function f(ByVal g As Object, ByVal x As String) As String
f = g(x)
End Function
*注意,这样你就可以传递任何功能;但您可以指定ByVal g As IStringFunction
来仅获取具有正确接口的子集Gary McGill's answer