python - VBA如何使用部分参数调用另一个函数内的函数

标签 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 中正确传递“部分”函数作为参数。我发现如何在 VBA 中传递“整个”函数 this post 。这个想法是将函数作为字符串传递,然后让 VBA 计算该字符串(我猜类似于 Python eval 等价物?)。但我不知道如果我的函数是部分的,即我希望它仅在第一个参数上成为一个函数,例如 lambda x: f(x, k) ,其中第二个参数位于主函数的上下文中。

感谢您提前提出任何建议。

最佳答案

我不了解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

关于python - VBA如何使用部分参数调用另一个函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301376/

相关文章:

python - 您如何查看交互式 Python 中的整个命令历史记录?

python - 从(或附近)具有相同名称的脚本导入库会引发 "AttributeError: module has no attribute"或 ImportError 或 NameError

excel - DAX日历动态假期功能

.net - 如何使用 EPPlus for .NET 将 Excel 工作表从一个文件复制到另一个文件

vba - 加密和保护 VBScript 和 VBA 代码的最有效方法是什么?

python - 我可以使用带有密码的 pyOpenSSL 生成私钥吗

python - bool 运算符如何在 python 中处理字符串

java - 每次读取一行/仅读取特定列并创建对象

excel - 将 SumProduct 函数转换为 VBA

excel - 如何编辑此代码以仅使用选择的行/单元格而不是整个工作表