UDF从返回数据计算CAGR

我想做一个UDF来计算给定范围的复合年增长率。

给函数的数据通常是月度返回数据,所以我需要:

  • 将范围内的每个单元格添加1
  • 将所有细胞相乘
  • 取(1 /(范围内的数字/ 12))的力量

如果我这样做,我会input公式=产品(rng + 1)^(1 /(Count(rng)/ 12)) – 1和数组inputCTRL + Shift + Enter

我已经尝试了两种不同的方式来完成这个工作。 首先是基本上做前面提到的公式在vba中。

Option Explicit Function CAGR(rng As Range) As Double Dim total As Double Dim n As Integer Dim pwr As Double Total = Application.FormulaArray="=Product(rng+1)" n = Application.WorksheetFunction.Count(rng) pwr = (1 / (n / 12)) CAGR = Application.WorksheetFunction.Power(total, pwr) - 1 End Function 

但是行

 Total=Application.formulaArray="=Product(rng+1)" 

不能工作presumebly因为我使用formulaArray函数错误…

我试过的另一种方法是使循环的function,我想在该范围中的每个单元格值加1,并将它们相乘。 (不是整个function)。

 Option Explicit Function CAGR2(rng As Range) As Double Dim cell As Variant Dim k As Double Dim n As Integer For Each cell In rng cell.Value = cell.Value + 1 Next cell k = Application.WorksheetFunction.Product(rng) CAGR2 = k End Function 

我在互联网上find的所有CAGR函数似乎都在价格数据上,所以我想强调这个函数应该根据回报数据(1%,-2%,3%等)来计算。

我一直在这个问题上苦苦挣扎几个小时,所以任何帮助将大大appriciated!

非常感谢

使用评估函数:

 CAGR = ActiveSheet.Evaluate("Product(" & rng.address(1,1,xlA1,True) & "+ 1)^(1/(Count(" & rng.address(1,1,xlA1,True) & ")/12))-1") 

我喜欢你的循环想法,并认为你在正确的轨道上。 build立你的第二块代码

 Option Explicit Function CAGR2(rng As Range) As Double Dim cell As Variant Dim n As Integer CAGR2 = 1 n = 0 For Each cell In rng CAGR2 = CAGR2 * (cell.Value + 1) n = n + 1 Next cell CAGR2 = CAGR2 ^ (1 / (n / 12)) End Function 

请注意,我跟踪的范围内的单元格的数量与n ,我们只积累了每个细胞的产品与CAGR2 。 一旦产品已经完全积累起来,我们就把它带到正确的指数。 我不确定,但是在说完之后你可能需要减去一个。