VBA 中的加权标准差

Weighted Standard Deviation in VBA

我正在尝试在 VBA 中编写加权标准差函数。 2 个范围输入应该输出一个值。然而,它 returns 一个 #value 错误。

编辑:添加了 worksheet.function

Public Function StDevWeighted(data As Range, weight As Range) As Double

    'https://stats.stackexchange.com/questions/6534/how-do-i-calculate-a-weighted-standard-deviation-in-excel
    
    Dim mean, top, bottom
    
    mean = WorksheetFunction.SumProduct(data, weight) / WorksheetFunction.Length(data)
    
    top = WorksheetFunction.SumProduct(weight, (data - mean) ^ 2)
    bottom = ((WorksheetFunction.Length(data) - 1) / WorksheetFunction.Length(data)) * WorksheetFunction.Sum(weight)
    
    StDevWeighted = WorksheetFunction.SQRT(top / bottom)
End Function

所以,很遗憾,您必须自己计算平方差,item-by-item,并将答案存储在一个临时数组中(请参阅注释了解原因)。我还没有检查过我的 pay-grade!

以上的数学...
Public Function StDevWeighted(rngData As Range, rngWeight As Range) As Double
    Dim dMean As Double
    Dim dTop As Double
    Dim dBottom As Double

    Dim vData As Variant
    vData = rngData
   
    dMean = WorksheetFunction.SumProduct(rngData, rngWeight) / rngData.Count

    Dim vSqDiff() As Variant
    ReDim vSqDiff(1 To UBound(vData, 1), 1 To UBound(vData, 2))

    For r = 1 To UBound(vData, 1)
        For c = 1 To UBound(vData, 2)
            vSqDiff(r, c) = (vData(r, c) - dMean) ^ 2
        Next c
    Next r

    dTop = WorksheetFunction.SumProduct(rngWeight, vSqDiff)
    dBottom = ((rngData.Count - 1) / rngData.Count) * WorksheetFunction.Sum(rngWeight)

    StDevWeighted = Sqr(dTop / dBottom)
End Function

PS。我直接使用调试器从我的电子表格中对此进行了测试。