Home » excel » excel – how to avoid averageifs #DIV/0! using VBA

excel – how to avoid averageifs #DIV/0! using VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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:

Sub Test1()
Dim i As Long

i = 10
Sheet1.Range("AB3").Formula = "=IFERROR(AVERAGEIFS(AF5:AF" & CStr(i) & ",AF5:AF" & CStr(i) & ",""<>n/a""),""N/A"")"
Sheet1.Range("B3").Value = Sheet1.Range("AB3").Value
End Sub

Sub Test2()
Dim strFormula As String
Dim i As Long

i = 10
strFormula = "=IFERROR(AVERAGEIFS(AF5:AF" & CStr(i) & ",AF5:AF" & CStr(i) & ",""<>n/a""),""N/A"")"
Sheet1.Range("AB3").Value = Application.Evaluate(strFormula)
End Sub

Answer:

I found another solution to my question:

to avoid the:

unable to get the average property of the worksheetfunction class

just remove WorksheetFunction from the formula.

That’s it.