[英]How do I call a function/return a value in VBA?
I am trying to code a method, and for every step I have to call another method (which I coded as a separate Sub).我正在尝试编写一个方法,并且对于每一步我都必须调用另一个方法(我将其编码为一个单独的 Sub)。
Sub implicit()
'Setting limits and stepsize
x0 = 0
xfinal = 100
h = 5
Dim y2 As Double
Dim y As Double
'Calculating number of intervals
n = (xfinal - x0) / h
'Setting initial value
y = 100000
'Loop for implicit method
For i = 1 To n
Call methodN(y)
y2 = y + h * (0.1 * y2 - 0.0000008 * y2 ^ 2)
Cells(2 + i, 3) = y2
y = y2
Next i
End Sub
'N method
Sub methodN(y)
y2 = y - (y * (1 - 0.1 * h + 0.0000008 * h * y) - y) / (1 - 0.1 * h + 0.0000016 * h * y)
End Sub
When I put Return y2 in the second sub as the last line I get a compiler error.当我将 Return y2 作为最后一行放在第二个 sub 中时,出现编译器错误。 I know I'm not calling the Sub properly and I'm not returning the y2 value.
我知道我没有正确调用 Sub 并且我没有返回 y2 值。
In VBA a Sub is a non returning method.在 VBA 中,Sub 是非返回方法。 You need to use Function instead, and then can Return a value
您需要使用 Function 代替,然后可以返回一个值
In short, it should look like this:简而言之,它应该如下所示:
Function methodNewton(y)
y2 = y - (y * (1 - 0.1 * h + 0.0000008 * h * y) - y) / (1 - 0.1 * h + 0.0000016 * h * y)
methodNewton = y2
End Function
or more simply:或更简单地说:
Function methodNewton(y)
methodNewton = y - (y * (1 - 0.1 * h + 0.0000008 * h * y) - y) / (1 - 0.1 * h + 0.0000016 * h * y)
End Function
and then call it this way instead:然后这样称呼它:
y2 = methodNewton(y)
but you are missing an h
variable, so maybe like this:但你缺少一个
h
变量,所以可能是这样的:
Function methodNewton(y, h)
methodNewton = y - (y * (1 - 0.1 * h + 0.0000008 * h * y) - y) / (1 - 0.1 * h + 0.0000016 * h * y)
End Function
and then call it like this然后这样称呼它
y2 = methodNewton(y, h)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.