Here is a UDF that I've used for a while. Works similiar to DMAX in that it
requires a fieldname, tablename, and accepts an optional criteria. It will
return a NULL if no records match the criteria.
Public Function fnMedian(ByVal Fieldname As String, ByVal Tablename As
String, _
Optional ByVal Criteria As String) As Variant
Dim strSQL As String, strCriteria As String
Dim rs As DAO.Recordset
Dim intRecCount As Integer, intPointer As Integer
strSQL = "SELECT [" & Fieldname & "] FROM [" & Tablename & "] "
strCriteria = " WHERE [" & Fieldname & "] IS NOT NULL"
If Len(Criteria) > 0 Then strCriteria = strCriteria & " AND " & Criteria
strSQL = strSQL & strCriteria & " ORDER BY [" & Fieldname & "]"
Set rs = CurrentDb.OpenRecordset(strSQL, , dbFailOnError)
'If no records in the recordset, return a Null value
If rs.EOF Then
fnMedian = Null
GoTo fnMedianExit
End If
rs.MoveLast
intRecCount = rs.RecordCount
rs.MoveFirst
'Move to the center record(s)
For intPointer = 2 To (intRecCount + 1) \ 2
rs.MoveNext
Next intPointer
fnMedian = Val(rs(0))
If intRecCount Mod 2 = 0 Then 'average center two values
rs.MoveNext
fnMedian = Val(fnMedian) + Val(rs(0))
fnMedian = fnMedian / 2
End If
fnMedianExit:
If Not rs Is Null Then
rs.Close
Set rs = Nothing
End If
Exit Function
fnMedianError:
MsgBox Err.Number, Err.Description
GoTo fnMedianExit
End Function
HTH
Dale
--
Don''t forget to rate the post if it was helpful!
Email address is not valid.
Please reply to newsgroup only.
TH said:
I am very new to Access and would like to calculate the median of various
groupings of data - I have no trouble grouping by average, min, max etc. but
I don't know how to calculate the median. Any help would be much appreciated.
TH