在VBA中为指定范围的平均值创建函数

时间:2019-02-20 22:06:22

标签: excel vba excel-formula

请帮助!

我需要在VBA中创建一个函数,该函数允许我根据指定的单元格范围返回平均值。

对于此功能,我想指定单元格的范围,使活动单元格的代码ID在该范围内,然后根据活动单元格对上下单元格进行平均。所附图片显示了我正在尝试做的事情。

enter image description here

到目前为止,这是我目前拥有的VBA功能,但我似乎无法使其完全正常工作:

VBA:

Function SpecialAVERAGE(rng As Range, LowerBound As Integer, UpperBound As Integer) As Double

Dim Origin As Range
Dim Total As Double
Dim Count As Integer
Dim Lower As Long
Dim Upper As Long
Dim A As Long
Dim B As Long

Set Origin = ActiveCell

For Each Cell In rng
    Lower = Range(Cell.Offset(-LowerBound, 0), Cells(Origin.Row, 1))
    A = wf.Sum(Lower)
    Upper = Range(Cell.Offset(UpperBound, 0), Cells(Origin.Row, 1))
    B = wf.Sum(Upper)
    Total = Total + Cell.Value + A + B
    Count = Count + 1

Next Cell

SpecialAVERAGE = Total / Count

End Function

任何方向都非常感谢!! 我知道= AVERAGE(OFFSET(....)))可能对此有所帮助,但是我也没有找到解决方案。

谢谢!!

1 个答案:

答案 0 :(得分:1)

无需过于复杂-只需使用上下边界来扩大WorksheetFunction.Average的行值,并使用一个单元格(而不是整个列)作为参考范围:

Function SPECIALAVERAGE(rng As Range, LowerBound As Integer, UpperBound As Integer) As Double

    SPECIALAVERAGE = WorksheetFunction.Average(Range(Cells(rng.Row - LowerBound, rng.Column), Cells(rng.Row + UpperBound, rng.Column)))

End Function

img1