6

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

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.

4

3 回答 3

6

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

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

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

complicatedFunction(x)

但是,L 和 U 必须是常数才能起作用。

FWIW,如果你真的在使用 VB.Net 方言,VB.Net 语法如下所示:

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
于 2014-05-12T18:18:11.330 回答
5

VB 中没有嵌套函数,无论是 VBA 还是 VB6 或 VB.NET。

将范围限制为 VBA,您的选择将是:

  • 使用GoSub,最古老的 VB 命令之一,已被弃用,不受欢迎,并且在 VB.NET 中没有等效的升级:

    Function mainActionHappensHere(L as Double, U as Double ...)
        Dim ResultOfCleaner As Variant
        ...
        x = 5 : GoSub cleaner                       'Many calls to this function
        'Use ResultOfCleaner here
        ...
        x = 42 : GoSub cleaner                      'Many calls to this function
        'Use ResultOfCleaner here
        ...
        Exit Function
    
    cleaner:
        ResultOfCleaner = complicatedFunction(x, L, U)
        Return
    End Function
    
  • 手动创建一个闭包。

    L定义一个将和U作为字段或属性公开的类。实例化类,设置LandU一次,然后调用Cleaner同样在该类中定义的函数,该函数complicatedFunction使用存储的Land调用U

    显然,这会产生一些开销。

于 2014-05-12T18:30:35.987 回答
-1

您可以使用此语法

Dim fSomeFunction As Func(Of String, Boolean) = Function(ByVal something As String) As Boolean
                                                                     Return True
                                                                 End Function
于 2019-06-14T12:30:34.763 回答