对数平均

时间:2018-03-14 17:18:21

标签: excel vba excel-vba

我正在开发一个自定义函数,用于计算范围的对数平均值。帖子logarithmic averaging question的答案是错误的,但这是一个起点。问题在于计算范围值的反对数(10 ^(0.1x))。这是我的第一篇文章,请原谅任何失误。

这是我的代码:

Function logavg(rngValues As Range) As Double

    Dim lSumofValues As Double
    Dim lCountofValues As Double
    Dim lAntilog As Double
    Dim rngLoop As Range

    lSumofValues = 0
    lAntilog = 0
    lCountofValues = rngValues.Count 'Get count of values in items in range

'For loop - add the antilogs of the values in the range - does not work
    For Each rngLoop In rngValues
        lAntilog = WorksheetFunction.Power(10, 0.1 * rngLoop.Value)
        lSumofValues = lSumofValues + lAntilog
    Next

'Perform calculation - logarithmic average
    logavg = 10 * Log(lSumofValues / lCountofValues)

End Function

我试过这个'for'循环,但它不起作用:

    For Each rngLoop In rngValues
        lSumofValues = lSumofValues + (10 ^ (0.1 * rngLoop.Value))
    Next

这个简单(算术)平均值的代码可以工作,所以我知道正在传输和使用范围值:

    For Each rngLoop In rngValues
    lSumofValues = lSumofValues + rngLoop.Value
    Next
    logavg = lSumofValues / lCountofValues

测试数据为:92.8,79.1,81.6,78.3,89.4,86.5,86.9

算术平均值为84.9,对数平均值为87.6。

计算B2:B8的对数平均值的两个Excel公式为:

a)数组公式= 10 * LOG(SUM(10 ^(0.1 * B2:B8))/ COUNT(B2:B8))和

b)标准公式= 10 * LOG(SUMPRODUCT(10 ^(0.1 * B2:B8))/ COUNT(B2:B8))

感谢。

2 个答案:

答案 0 :(得分:2)

这是一个使用所有VBA函数的方法:

Function logAvg(myRng As Range) As Double
    Dim myCount As Long
    Dim D As Double
    Dim I As Long
    Dim V

    V = myRng
    For I = 1 To UBound(V, 1)
        D = D + 10 ^ (V(I, 1) * 0.1)
    Next I

    myCount = UBound(V, 1)
    D = D / myCount

    D = Log(D) / Log(10)
    logAvg = 10 * D

End Function

答案 1 :(得分:1)

微小的变化:

Function logavg(rngValues As Range) As Double
    With Application.WorksheetFunction
        Dim lSumofValues As Double
        Dim lCountofValues As Double
        Dim lAntilog As Double
        Dim rngLoop As Range

        lSumofValues = 0
        lAntilog = 0
        lCountofValues = rngValues.Count 'Get count of values in items in range

    'For loop - add the antilogs of the values in the range - does not work
        For Each rngLoop In rngValues
            lAntilog = .Power(10, 0.1 * rngLoop.Value)
            lSumofValues = lSumofValues + lAntilog
        Next

    'Perform calculation - logarithmic average
        logavg = 10 * .Log10(lSumofValues / lCountofValues)
    End With
End Function

enter image description here

我的数据位于 B1 B7