VBA中可以使用嵌套函数吗? [英] Are nested functions possible in VBA?

查看:1007
本文介绍了VBA中可以使用嵌套函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过剥离私有作用域内的函数中的参数来清理代码,如下所示:

I'm trying to clean up code by stripping parameters from a function within a private scope, like this:

Function complicatedFunction(x as Double, param1 as Double, param2 as Double)
    ...
End Function

Function mainActionHappensHere(L as Double, U as Double ...)
    Function cleaner(x)
        cleaner = complicatedFunction(x, L, U)
    End Function
    ...
    cleaner(x)                       'Many calls to this function
    ...
End Function

这可能吗?编译器抱怨期望结束函数",因为我在结束外部函数之前先开始一个函数. Google毫无帮助:( PS我无法在mainActionHappensHere()之外定义清洁器(),因为那样的话,正确的L和U不会传递给它.

Is this possible? Compiler complains, "Expected End Function", since I'm beginning a function before ending the outer one. And Google is no help :( PS I can't define cleaner() outside of mainActionHappensHere(), since then the correct L and U won't get passed into it.

推荐答案

VB.Net可以做到这一点,但我不相信VBA可以做到.

VB.Net can do this, but I don't believe VBA can.

重载函数或可选参数可能会以其他方式帮助您简化此代码的两个功能.这是使用可选参数的示例:

Two features that might help you simplify this code in other ways are overloaded functions or optional parameters. Here's an example using optional parameters:

Function complicatedFunction(x as Double, Optional param1 as Double = L, Optional param2 as Double = U) As Object
...
End Function

complicatedFunction(x)

但是,L和U必须是常量才能起作用.

However, L and U must be constants for this to work.

FWIW,如果事实证明您确实在使用VB.Net方言,则VB.Net语法如下所示:

FWIW, and in case it turns out that you're really working with a VB.Net dialect, the VB.Net syntax looks like this:

Sub complicatedFunction(x as Double, param1 as Double, param2 as Double) 
    ...
End Sub

Function mainActionHappensHere(L as Double, U as Double ...)
    Dim cleaner As Func(Of Double, Object) = 
        Function(x) 
            Return complicatedFunction(x, L, U)
        End Function

    Dim y = cleaner(x)                       'Many calls to this function
    ...
End Function

这篇关于VBA中可以使用嵌套函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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