Averaging duplicates (VBA)

mhorsnell

New Member
Joined
Nov 2, 2017
Messages
2
Hi everyone,

I have to write a script that will take a two dimensional range entered by the user, sort the data into ascending numerical order, average any duplicates in the range and then perform linear interpolation (or extrapolation) on the data to find a y value for an x value entered by the user.

For averaging the duplicate values, I am struggling, I have written this:


For i = 1 To k
yrsum = yrsortav(i)
yrcount = 1 'yrcount is the number of y values who have the same x value (duplicates)
If xrsort(i) = xrsort(i + 1) Then
yrcount = yrcount + 1 'adds 1 to yrcount for every duplicate
yrsum = yrsum + yrsortav(i + 1) 'y values with same x value are added together
yrav = yrsum / yrcount ' y average = sum of duplicates/by number of duplicates
yrsortav(i) = yrav ' relevant cells in range overwritten with new average value of y
yrsortav(i + 1) = yrav
End If
Next i

k is equal to the number of rows in the range minus 1, xrsort is my sorted x range (the left-hand column of the 2D range), yrsort is the sorted y range (right hand column of 2D range). yrcount is the number of duplicates, for instance, if xrsort(1) = xrsort(2), yrcount will be 2, and the sum of their corresponding y values will be divided by two to produce an average - yrav

As it currently is, this code works if there are two values of y with the same x, it nearly works for 3 values, it does some kind of averaging, but does not give the right numbers.

Please can you advise me what I am doing wrong and how I might fix it

Thanks in Advance
Michael
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.

Forum statistics

Threads
1,223,610
Messages
6,173,336
Members
452,510
Latest member
RCan29

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