I have the below code:
Sheet1.Range("AB3").Value = Application.WorksheetFunction.AverageIfs( _
.Range("AB5:AB" & CStr(i)), _
.Range("AB5:AB" & CStr(i)), _
">=0", .Range("AB5:AB" & CStr(i)), "<>N/A")
To get the average of a range and exclude -ve values and N/A values, but there is a moment when all range is N/A, so I’m getting the following error:
unable to get the average property of the worksheetfunction class
To avoid that I tried this:
Sheet1.Range("AB3").Value = Application.WorksheetFunction.IfError( _
Application.WorksheetFunction.AverageIfs( _
.Range("AB5:AB" & CStr(i)), _
.Range("AB5:AB" & CStr(i)), ">=0", _
.Range("AB5:AB" & CStr(i)), "<>N/A"), "N/A")
But with no luck. Any help will be appreciated.
EDIT:
In excel it works ok, but not in vba (in the code behind)
Just doing a little test in excel it works fine:
=IFERROR(AVERAGEIFS(AF5:AF10,AF5:AF10,"<>n/a"),"N/A")
in the above formula if data in range “AF5:AF10” is all “n/a”, the formula returns “N/A” which is correct.
I’d just apply the formula to the cell in code. Here’s two ways, one that puts the formula in the activecell and then “pastes” over it as a value, one that evaluates the formula and then puts that value in the activecell: