VBA写入功能结果进入活动和偏移单元

问题描述

我创建了一个具有两个结果的函数:t_final和q_final(t表示时间,q表示生产率)。

当我在VBA中使用第一个编码而没有明确提及该单元并且只有一个结果(t_final)时,结果出现。但是我需要两个结果并将它们写在连续的单元格中。

一个代码给了我计算结果。第二个只给我#value。

 Function t_final(qi,Di,b,q_limit)
'qi: initial rate
'Di: initial decline rate
'b:  decline exponent
'q_limit : economic limit for rate
'Nominal decline is the instantaneous decline rate
    Dim i,t,q_final
    i = 1
    Do
    t = i * 30
    q_final = arpsrate(qi,t)
    i = i + 1
    t_final = t
    Loop Until q_final < q_limit

 End Function
'The second code is the same as the first one with additional:
ActiveCell.Offset(0,1).Value = t_final
ActiveCell.Offset(0,2).Value = q_final

感谢您为我的问题支付利息!

解决方法

如注释中所述,如果需要多个输出,则需要从UDF返回一个数组。

Function t_final(qi,Di,b,q_limit)
    'qi: initial rate
    'Di: initial decline rate
    'b:  decline exponent
    'q_limit : economic limit for rate
    'Nominal decline is the instantaneous decline rate
    Dim i,t,q_final,t_f
    i = 1
    Do
        t = i * 30
        q_final = arpsrate(qi,t)
        i = i + 1
        t_f = t
    Loop Until q_final < q_limit

    t_final = Array(t_f,q_final)
 End Function

然后像这样使用

{=t_final([arguments here])}

使用 Ctrl + Shift + Enter

在两个单元格中(跨)输入