python - 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 中传递“整个”函数。这个想法是将函数作为字符串传递,然后让 VBA 评估字符串(我猜这类似于 Pythoneval
等价物?)。但是我不知道如果我的函数是部分的,这将有什么帮助,即我希望它只在第一个参数上成为一个函数,就像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
推荐阅读
- angular - 使用 express.js 为 angular8 ssr 在服务器上提供文件
- javascript - TypeError:无法读取 ReactJs 中未定义的属性“concat”
- sip - 我在 Edgerouter X 上的 VoIP 设置有什么问题(德国电信)
- beautifulsoup - beautifulSoup 4 适用于 python2.6?
- python - 内核重启后如何重新加载jupyter笔记本?
- flutter - 如何修复 - 在调试模式下登录的 APK 问题 - Flutter 应用
- python - 如何将值从python中的配置文件传递给变量
- sql-server - 如何在 SSIS 作业步骤属性中使用环境文件
- mysql - 从单独的表中添加计数总计
- javascript - 使用 Redux 处理 UI 状态可以吗?