[英]VBA - use visible cells only for weighted average UDF
For calculating a weighted average I use the following simple custom function VBA code: 为了计算加权平均值,我使用以下简单的自定义函数VBA代码:
Function wgtavg(values As Range, weights As Range)
wgtavg = WorksheetFunction.SumProduct(values, weights) / WorksheetFunction.Sum(weights)
End Function
I want a function that considers only visible cells - Can anyone suggest a solution? 我想要一个只考虑可见细胞的功能 - 任何人都可以提出解决方案吗?
edit: I figured this out: 编辑:我想出来了:
Function wgtavg(values As Range, weights As Range)
counter = 0
xSumproduct = 0
xSum = 0
For Each xVal In values
counter = counter + 1
If xVal.Rows.Hidden = False Then
If xVal.Columns.Hidden = False Then
xSumproduct = xSumproduct + (xVal * weights(counter))
xSum = xSum + weights(counter)
End If
End If
Next
wgtavg = xSumproduct / xSum
End Function
Seems to work but I dont know how to integrate the visibility check of the weights. 似乎工作,但我不知道如何整合权重的可见性检查。
Use SpecialCells() method 使用SpecialCells()方法
Function wgtavg(values As Range, weights As Range)
wgtavg = WorksheetFunction.SumProduct(values.SpecialCells(xlCellTypeVisible), weights.SpecialCells(xlCellTypeVisible)) / WorksheetFunction.Sum(weights.SpecialCells(xlCellTypeVisible)))
End Function
How about: 怎么样:
Function wgtavg(values As Range, weights As Range) As Double
Dim i As Long
For i = 1 To values.Count
If values(i).EntireRow.Hidden = False Then
wgtavg = wgtavg + values(i) * weights(i)
End If
Next i
wgtavg = wgtavg / Application.WorksheetFunction.Subtotal(109, weights)
End Function
Try this: 尝试这个:
Function wgtavg(values As Range, weights As Range) As Variant
Dim counter As Long
Dim xSumproduct As Double
Dim xSum As Double
'Error if there are different numbers of values and weights
If values.Cells.Count <> weights.Cells.Count Then
wgtavg = CVErr(xlErrRef)
Exit Function
End If
'Initialise SumProduct and Sum (just in case Dim no longer does so)
xSumproduct = 0
xSum = 0
'Loop through each cell
For counter = 1 to values.Cells.Count
'Check to if value or weight is hidden
If Not (values(counter).Rows.Hidden Or _
values(counter).Columns.Hidden Or _
weights(counter).Rows.Hidden Or _
weights(counter).Columns.Hidden) Then
'Error if either value or weight is error
If IsError(values(counter)) Or _
IsError(weights(counter)) Then
wgtavg = CVErr(xlErrNA)
Exit Function
End If
'Error if either value or weight is not numeric
If Not (IsNumeric(values(counter).Value) And _
IsNumeric(weights(counter).Value)) Then
wgtavg = CVErr(xlErrNA)
Exit Function
End If
'Maintain running total of SumProduct and Sum
xSumproduct = xSumproduct + values(counter).Value * _
weights(counter).Value
xSum = xSum + weights(counter).Value
End If
Next
'Calculate weighted average
wgtavg = xSumproduct / xSum
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.