AVERAGEIF IN CODE, BUT A SELECTION OF CELLS

SQUIDD

Well-known Member
Joined
Jan 2, 2009
Messages
2,104
Office Version
  1. 2019
  2. 2016
Platform
  1. Windows
Hi

So i have a few scattered cells that i need to get the average of them

The below works until one of these figures is a "0", then it messes with my average.

VBA Code:
Set myrng = Union(Cells(2, 2), Cells(4, 2))
my_average = Application.WorksheetFunction.Average(myrng)

so i wanted to modify this to averageif, but i am not having an sucsess, perhaps i am chasing something that will not work.

and help or pointers would be great.

thanks

dave
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
There's (at least) a couple of different ways you could do this using VBA. The first option below calculates the AverageIf. If your range is simply cells B2 & B4 - and there is nothing but a blank cell in B3 - then the second option is simpler. Neither option has error trapping if both cells contain zeros.

VBA Code:
Sub Squidd1()
    Dim myrng As Range, c As Range, mycount As Long, my_average As Long
    Set myrng = Union(Cells(2, 2), Cells(4, 2))
    
    For Each c In myrng
        If c <> "0" Then mycount = mycount + 1
    Next
    
    my_average = Application.Sum(myrng) / mycount
    MsgBox my_average
End Sub

Sub Squidd2()
    Dim myrng As Range, my_average As Long
    Set myrng = Range(Cells(2, 2), Cells(4, 2))
    
    my_average = Application.AverageIf(myrng, "<>0")
    MsgBox my_average
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,611
Messages
6,120,509
Members
448,967
Latest member
screechyboy79

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top