Hello,
I was curious if it's possible to modify this code (found of Microsoft's help site, not sure if it's the best or should use something else?) so that I can group the median in Access by separate fields. I have a table that shows part number and supply time -- when I use this code it will give me the overall median; although ideally maybe there's a way to have a column that groups the part number and find the median supply time for each.
Public Function MedianOfRst(RstName As String, fldName As String) As Double
'This function will calculate the median of a recordset. The field must be a number value.
Dim MedianTemp As Double
Dim RstOrig As Recordset
Set RstOrig = CurrentDb.OpenRecordset(RstName, dbOpenDynaset)
RstOrig.Sort = fldName
Dim RstSorted As Recordset
Set RstSorted = RstOrig.OpenRecordset()
If RstSorted.RecordCount Mod 2 = 0 Then
RstSorted.AbsolutePosition = (RstSorted.RecordCount / 2) - 1
MedianTemp = RstSorted.Fields(fldName).Value
RstSorted.MoveNext
MedianTemp = MedianTemp + RstSorted.Fields(fldName).Value
MedianTemp = MedianTemp / 2
Else
RstSorted.AbsolutePosition = (RstSorted.RecordCount - 1) / 2
MedianTemp = RstSorted.Fields(fldName).Value
End If
MedianOfRst = MedianTemp
End Function
Thanks for any help!
Mike
Sorry -- didn't read the rules before I posted
Public Function MedianOfRst(RstName As String, fldName As String) As Double 'This function will calculate the median of a recordset. The field must be a number value. Dim MedianTemp As Double Dim RstOrig As Recordset Set RstOrig = CurrentDb.OpenRecordset(RstName, dbOpenDynaset) RstOrig.Sort = fldName Dim RstSorted As Recordset Set RstSorted = RstOrig.OpenRecordset() If RstSorted.RecordCount Mod 2 = 0 Then RstSorted.AbsolutePosition = (RstSorted.RecordCount / 2) - 1 MedianTemp = RstSorted.Fields(fldName).Value RstSorted.MoveNext MedianTemp = MedianTemp + RstSorted.Fields(fldName).Value MedianTemp = MedianTemp / 2 Else RstSorted.AbsolutePosition = (RstSorted.RecordCount - 1) / 2 MedianTemp = RstSorted.Fields(fldName).Value End If MedianOfRst = MedianTemp End Function
I'd think it'd be easier to do with a SQL statement, something like this:
SELECT TOP 1 supplytime FROM (SELECT TOP 50 PERCENT supplytime FROM tablename GROUP BY partnumber) GROUP BY partnumber;
Is your code running too slowly?
Does your workbook or database have a bunch of duplicate pieces of data?
Have a look at this article to learn the best ways to set up your projects.
It will save both time and effort in the long run!
Dave
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks