我想计算加权平均值和加权标准差。我能够计算平均值而不是标准偏差。我应该怎么做呢?
With Application.WorksheetFunction
Range("AH" & 2) = .SumProduct(Columns(7), Columns(8)) / .Max(Columns(8)) 'This code works very well. It calculates the mean
Dim Nprime As Double
Nprime = .CountIf(Range("H2:H" & lengthRows), "<>" & 0) 'This code works well
Range("AM" & 2) = 2 * .SQRT(.SumProduct((Columns(7) - Columns(34)) ^ 2, Columns(8)) / ((Nprime - 1) * .Sum(Columns(8))) / Nprime) 'This line does not work. It should calculate the weighted standard deviation.
Range("AM" & 2) = Evaluate("2*SQRT(SumProduct((Columns(7) - weightedMean)^2), Columns(8)) / ((Nprime - 1) * .Sum(Columns(8))) / Nprime)") 'This line code evaluates with an answer of #VALUE! probably due to the titles in Row1, how do I fix the code to only evaluate the numerical values within the columns?
End With
答案 0 :(得分:1)
对于“加权”AV或SD没有保留,但也许您可以调整以下内容。代码加载数组中的数据,然后获得AV和SD。
Private Sub CommandButton1_Click()
Dim MyArray() As Variant
Dim lAV As Double
Dim lSD As Double
Dim i As Integer
lLastRow = Worksheets("MyData").UsedRange.Rows.Count
ReDim MyArray(1 To 1) As Variant
For i = 1 To lLastRow
MyArray(UBound(MyArray)) = Worksheets("MyData").Cells(i, 7).Value * Worksheets("MyData").Cells(i, 8).Value
ReDim Preserve MyArray(1 To UBound(MyArray) + 1) As Variant 'now array is 1 element longer
Next
'Now MyArray contains desired data.
'Get average and SD
lAV = Application.WorksheetFunction.Average(MyArray)
lSD = Application.WorksheetFunction.StDev(MyArray)
'write results (be shure not to overwrite your data)
Worksheets("MyData").Cells(1, 10) = "Average: "
Worksheets("MyData").Cells(1, 11) = lAV
Worksheets("MyData").Cells(2, 10) = "SD: "
Worksheets("MyData").Cells(2, 11) = lSD
End Sub