PDA

View Full Version : Looping through and finding average of data



username1
12-12-2011, 04:54 AM
Hey guys,

This should be simple but I'm not getting it.

So I have data with prices, and it is broken up by "group." The group size is variable. Also, there are two different types of prices according to "type" Something like this:



Group Type Price
1 A 122
1 A 125
1 A 133
1 B 65
1 A 120
2 B 72
2 B 72
2 A 115
3 A 115
3 B 80
4 B 80
4 B 83
4 A 100
4 A 100


So basically what I'm trying to do is first find a group. I do this by setting a value, s=1, at the beginning and doing a for-each to go through the used rows while using a nested if to see if it matches s. I obviously +1 whenever we get through the group. After that I for-each back through the group, and If is nested again to see what data type it is and then to collect price.

That being said, it isn't working, and I haven't even begun to figure out how to average it. Here is my current code on the actual pertinent part.

For Each cell4 In raw.Range("G5:G" & i)
If cell4.Value = s Then

If raw.Range("C" & cell4.Row) = "A" Then
APrice = raw.Range("F" & cell4.Row)
ElseIf raw.Range("C" & cell4.Row) = "B" Then
BPrice = raw.Range("F" & cell4.Row)
End If
End If
End For


This is obviously pulling the price from another data point, but this is all non-pertinent I think. I just wanted to show code so it didn't look like I had nothing coded on my own!

p45cal
12-12-2011, 05:28 AM
something like this? (untested):For Each cell4 In raw.Range("G5:G" & i)
If cell4.Value = s Then
Select Case raw.Range("C" & cell4.Row).Value
Case "A"
APrice = APrice + raw.Range("F" & cell4.Row).Value
ACount = ACount + 1
Case "B"
BPrice = BPrice + raw.Range("F" & cell4.Row).Value
BCount = BCount + 1
End Select
End If
Next cell4
GroupAaverage = APrice / ACount
GroupBaverage = BPrice / BCount

Aflatoon
12-12-2011, 05:31 AM
Would not a pivot table be much simpler?

p45cal
12-12-2011, 05:44 AM
Would not a pivot table be much simpler?It would.

shrivallabha
12-12-2011, 06:39 AM
If you are using Excel 2007+ version then you can use AVERAGEIF function. See attachment.