107

I have a column with average(K23:M23) that starts out with #DIV/0! when the K23 through M23 cells are empty. Preferably I'd like to only do the average of cells that contain non-zero, non-blank values. I think it's possible using the query command:

https://docs.google.com/support/bin/answer.py?hl=en&answer=159999

But their example doesn't help me.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Aaron
  • 2,154
  • 5
  • 29
  • 42

5 Answers5

195

Wrap your formula with IFERROR.

=IFERROR(yourformula)
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Nik
  • 1,982
  • 1
  • 13
  • 3
  • 8
    This seems to be the simplest answer, although I wish google would add functions to allow checking for specific types of errors. Wrapping the function in a generic IFERROR makes it harder to debug if a different error is occurring. – Brionius Aug 12 '15 at 03:44
  • 2
    This breaks some very basic principles in logic and programming. If you know what error/exception you're avoiding, then you should explicitly handle it that way. Peregrination's answer is better in that sense. But I'll post yet another answer. – Suamere Nov 11 '16 at 16:41
  • 7
    Might help to know you can specify a default value: `=IFERROR(K23/M23, "Invalid data")`. [Source](https://support.google.com/docs/answer/3093304?hl=en) – rideron89 Sep 19 '19 at 17:33
48

You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.

A simple example:

=IF(B1=0;"";A1/B1)

This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.

In your case of running an average, you could check to see whether or not your data set has a value:

=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))

If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.

Fedir RYKHTIK
  • 9,844
  • 6
  • 58
  • 68
peregrination
  • 2,460
  • 1
  • 25
  • 21
7

Wrapping the existing formula in IFERROR will not achieve:

the average of cells that contain non-zero, non-blank values.

I suggest trying:

=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")
pnuts
  • 58,317
  • 11
  • 87
  • 139
2

Since you are explicitly also asking to handle columns that haven't yet been filled out, and I assume also don't want to mess with them if they have a word instead of a number, you might consider this:

=If(IsNumber(K23), If(K23 > 0, ........., 0), 0)

This just says... If K23 is a number; And if that number is greater than zero; Then do something ......... Otherwise, return zero.

In ........., you might put your division equation there, such as A1/K23, and you can rest assured that K23 is a number which is greater than zero.

Suamere
  • 5,691
  • 2
  • 44
  • 58
1

Check if the column has text format. Apply number formatting to the cells you're using in the average function.

Niloct
  • 9,491
  • 3
  • 44
  • 57