我创建了一个简单的CAGR公式,它允许我根据给定的输入计算CAGR - 第一个周期,最后一个周期和周期数。
现在,我希望能够在选定的单元格范围内运行公式。我想不出任何花哨而简单的方法。宏本身应该能够将范围的最左边的单元格识别为第一个时段,最右边的时间识别为最后一个时段,并计算要提供时段数量的单元格数。
你能帮帮我吗?
我的CAGR公式宏看起来像这样:
Public Function CAGR(First, Last, Periods)
CAGR = ((Last / First) ^ (1 / Periods)) - 1
End Function
提前致谢。 保罗
答案 0 :(得分:0)
您可以像这样访问当前选定的范围:
Application.ActiveWorkbook.ActiveSheet.range(Application.Selection.Address)
我会把剩下的留给你,但如果你发表评论就会被卡住,我会给予更多的指导:)
答案 1 :(得分:0)
首先,我们需要一个输入范围,可以是一行宽或一列高(参见检查部分)。然后行或列模式的计算有点不同(参见代码中的注释)。
您可以在任何Excel单元格中使用该功能,例如......
=CAGR(A1:F1)
输入为行模式=CAGR(A1:A6)
输入为列模式=CAGR(A1:B5)
此输入无效,因为row.count
和column.count
为>1
,这将返回错误:#REF!
或者像VBA一样......
Public Sub MsgCagrOfSelection()
MsgBox CAGR(Selection) 'MessageBox the CARG result of the current selected cells
End Sub
Option Explicit
Public Function CAGR(rngInput As Range) As Variant 'needs to be variant so we can return errors too
' first we do some checking
' input range has to be one column or one row only
If rngInput.Columns.Count > 1 And rngInput.Rows.Count > 1 Then
CAGR = CVErr(xlErrRef)
Exit Function
End If
Dim First As Double
Dim Last As Double
Dim Periods As Long
' calculation is a bit different if we have a column or row as input range
If rngInput.Columns.Count > 1 Then ' we have one row
First = rngInput.Resize(1, 1).Value
Last = rngInput.Resize(1, 1).Offset(ColumnOffset:=rngInput.Columns.Count - 1).Value
Periods = rngInput.Columns.Count
Else ' we have one column
First = rngInput.Resize(1, 1).Value
Last = rngInput.Resize(1, 1).Offset(RowOffset:=rngInput.Rows.Count - 1).Value
Periods = rngInput.Rows.Count
End If
' first value has not to be 0 we can't divide by 0
If First = 0 Then
CAGR = CVErr(xlErrDiv0)
Exit Function
End If
CAGR = ((Last / First) ^ (1 / Periods)) - 1
End Function