我想在excel中编写一个函数。如果我有5个值,它应该返回值的平均值,如果任何值小于0,则不应计入平均值。到目前为止,我知道如何处理一个值,但是如果传递范围,我不知道如何处理,例如
= process_myfunction(A1:A10)
答案 0 :(得分:1)
试试这个
Function process_myfunction(rng As Range)
Dim cel As Range
Dim rngCnt As Long, rngSum As Long
For Each cel In rng
If cel.Value >= 0 Then 'check if cell value > 0
rngSum = rngSum + cel.Value 'sum cell value
rngCnt = rngCnt + 1 'count cell value
End If
Next cel
process_myfunction = rngSum / rngCnt 'calculate mean
End Function
如果您将此UDF用于非连续范围,则将函数写为
=process_myfunction((B2:B5,E2:E4,H2))