VBA如何在带有局部参数的另一个函数内调用函数

时间:2019-08-01 03:18:30

标签: python excel vba

因此,我想将以下Python代码转换为VBA(仅为说明问题的玩具示例,省略了详细信息)。

def numerical_integration(fun, a, b):
    """

    :param fun: callable 
    :param a, b: float
    :return: float
    """
    # do something based on both fun and a, b
    res = ...
    return res


def h(x, k):
    """
    helper func
    :param x: float, main arg
    :param k: float, side param
    :return: float
    """
    # calc based on both x and k
    res = ...
    return res


def main_function(k):
    """

    :param k: float 
    :return: float
    """
    a, b = 0.0, 1.0
    res = numerical_integration(fun=lambda x: h(x, k), a=a, b=b)
    return res

问题是我不知道如何在VBA中正确传递诸如“部分”函数之类的参数。我在this post中找到了如何在VBA中传递“整个”函数。这个想法是将函数作为字符串传递,然后让VBA评估字符串(我猜是类似Python eval的东西吗?)。但是我不知道如果我的函数是部分函数,​​那怎么办呢?也就是说,我只希望像lambda x: f(x, k)这样的第一个参数成为函数,而第二个参数位于主函数的上下文中。

感谢您的任何建议。

2 个答案:

答案 0 :(得分:1)

我不了解Python和“部分”功能,但是我尝试使用一个对象来替换它。 我创建了一个类模块,试图模仿“部分”功能,具有可选参数和默认值。

Public defaultX As Double
Public defaultY As Double

Public Function h(Optional x As Variant, Optional y As Variant) As Double

    ' The IsMissing() function below only works with the Variant datatype.

    If (IsMissing(x)) Then
        x = defaultX
    End If
    If (IsMissing(y)) Then
        y = defaultY
    End If

    h = x + y

End Function

然后,我决定在numeric_integration中使用“ CallByName”函数。 这是主要的模块代码:

Public Function numerical_integration(fun As clsWhatEver, funName As String, a As Double, b As Double) As Integer

    Dim r1 As Double, r2 As Double

    ' CallByName on the "fun" object, calling the "funName" function.
    ' Right after "vbMethod", the parameter is left empty
    ' (assuming default value for it was already set).
    r1 = CallByName(fun, funName, VbMethod, , a)
    r2 = CallByName(fun, funName, VbMethod, , b)

    numerical_integration = r1 + r2

End Function

Public Function main_function(k As Double) As Double
    Dim res As Double

    Dim a As Double, b As Double
    a = 0#
    b = 1#

    Dim oWE As New clsWhatEver
    ' Sets the default value for the first parameter of the "h" function.
    oWE.defaultX = k

    res = numerical_integration(oWE, "h", a, b)

    main_function = res

End Function

答案 1 :(得分:0)

我真的不确定您要问什么,但是如果您要尝试将第一个函数的结果作为第二个参数的传递,则...

Function numerical_integration(fun, a, b)
    numerical_integration = 1
End Function

Function h(x, k)
    h = 0
End Function

Sub main()
    Debug.Print numerical_integration(h(1, 2), 3, 4)
End Sub

(是的,这些都应该是强类型变量)