【问题标题】:Create Function for Average of Specified Range in VBA在VBA中为指定范围的平均值创建函数
【发布时间】:2019-02-21 15:36:08
【问题描述】:

请帮忙!

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

对于这个函数,我想指定单元格的范围,让代码 ID 成为该范围内的活动单元格,然后根据活动单元格对上方和下方的单元格进行平均。所附图片显示了我正在尝试做的事情。

这是我目前拥有的 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(.... ))) 可能对此有所帮助,但我也没有找到解决方案。

谢谢!!

【问题讨论】:

    标签: excel vba excel-formula


    【解决方案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
    

    【讨论】:

    • 非常感谢!我会试试看的!!
    • 做了我需要的!谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 2021-03-29
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多