gpt4 book ai didi

excel - 在VBA函数中计算二变量函数的值

转载 作者:行者123 更新时间:2023-12-04 22:19:39 28 4
gpt4 key购买 nike

我有一个函数f(x,y) = e^(x+y)并在 VBA 中像这样运行:

Function Test(n As Integer, x0 As Double, xk As Double, y0 As Double, yk As Double) As Double()

Dim i As Integer
Dim j As Integer
Dim Tablica() As Double
ReDim Tablica(0 To n, 0 To n)
For i = 0 To n
For j = 0 To n
Tablica(j, i) = Exp(x0 + i * (xk - x0) / n + y0 + j * (yk - y0) / n)
Next j
Next i
Test = Tablica

End Function
有没有办法重写此代码以使用任何函数,如 f(x,y) = x+y ETC。?

最佳答案

我将您的问题解释为如何使数学函数成为函数 test 的输入参数.在VBA中没有很好的方法可以做到这一点,但是你可以做的是在代码模块中定义函数然后使用Application.Runtest 内部按名称调用函数.
概念证明:

Function test(f As String, n As Integer, x0 As Double, xk As Double, y0 As Double, yk As Double) As Double()
Dim i As Long, j As Long
Dim Tablica() As Double
ReDim Tablica(0 To n, 0 To n)

For i = 0 To n
For j = 0 To n
Tablica(j, i) = Application.Run(f, x0 + i * (xk - x0) / n, y0 + j * (yk - y0) / n)
Next j
Next i
test = Tablica
End Function

'used like:

Function g(x As Double, y As Double) As Double
g = x - y
End Function

Sub test2()
Range("A1:D4").Value = test("g", 3, 0, 1, 3, 4)
End Sub
请注意,您不需要命名被调用函数 f ,所以 test可以使用多种功能。不幸的是,VBA 缺少匿名函数的概念,因此您仍然需要将函数定义为 VBA 函数(或编写自己的解析器)。

关于excel - 在VBA函数中计算二变量函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65234389/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com