简体   繁体   English

如何使用产品公式聚合excel UDF中的返回

[英]How to aggregate returns in an excel UDF using the product formula

I am trying to put the below formula into a UDF so that I can get a cumulative return when I aggregate monthly returns. 我试图将以下公式放入UDF中,以便在汇总月度回报时获得累积回报。

In excel the formula has to be recognized as an array so when I type it in I press Ctrl + Shift + Enter to get the {} brackets around the formula. 在excel中,必须将公式识别为数组,因此当我在其中键入时,按Ctrl + Shift + Enter以获得公式周围的{}括号。

Does anyone know how to do this? 有谁知道如何做到这一点?

I want to be able to just type in returns_calc() and select the range that would fit into the returns variable below. 我希望能够只输入returns_calc()并选择适合下面的returns变量的范围。

{=(PRODUCT(1+returns/100)-1)*100}

You can use the [ ] notation in Application.Evaluate to calculate Array Formulas in VBA. 您可以使用Application.Evaluate[ ]表示法来计算VBA中的数组公式。 Your above formula can be called in VBA in just 1 line as shown below 您可以在VBA 中仅在一行中调用上面的公式,如下所示

Sub Sample()
    MsgBox Application.Evaluate(["=(PRODUCT(1+returns/100)-1)*100"])
End Sub

Now modifying it to accept a range in a function, you may do this as well 现在修改它以接受函数中的范围,您也可以这样做

Function returns_calc(rng As Range) As Variant
    On Error GoTo Whoa

    Dim frmulaStr As String

    frmulaStr = "=(PRODUCT(1+(" & rng.Address & ")/100)-1)*100"
    returns_calc = Application.Evaluate([frmulaStr])

    Exit Function
Whoa:
    returns_calc = "Please check formula string" 'or simply returns_calc = ""
End Function

EXAMPLE SCREENSHOT 示例屏幕截图

在此输入图像描述

Something like this 像这样的东西

Public Function Range_Product(theRange As Variant)
    Dim var As Variant
    Dim j As Long

    var = theRange.Value2
    Range_Product = 1#
    For j = LBound(var) To UBound(var)
        Range_Product = Range_Product * (1 + var(j, 1) / 100)
    Next j

    Range_Product = (Range_Product - 1) * 100
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM