2017-08-26 76 views
-1

我想在excel中編寫函數。如果我有5個值,它應該返回值的平均值,如果任何值小於0,則不應計算爲平均值。到目前爲止,我知道如何處理一個值,但我不,如果範圍是通過例如如何在Excel中處理範圍

如何處理

= process_myfunction(A1:A10)

+0

'= averageif()'定義您的範圍,使ciriteria「> = 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 

enter image description here

如果您正在使用此UDF的非連續範圍,然後寫功能

=process_myfunction((B2:B5,E2:E4,H2)) 

enter image description here