My first attempt was a bare minimum, in accordance with the op's post.
Here's a more concise version.
(untested... the rs.Move command may need to be offset by one to get the
actual middle value...)
Public Function GetMedianValue(sSource As String, _
sField As String, _
Optional sWhere As String _
) As Double
'Returns Null on NonNumeric sField or No Records
'sSource = Source Table or Query
'sField = Field to get median from
'sWhere = Optional Where clause (excluding WHERE keyword)
On Error Goto Err_Proc
Dim Ret As Double, bRSOpen As Boolean
'--------------------
Dim rs As DAO.Recordset
Dim bEvenNumOfRecs As Boolean
Dim dblTemp As Double 'Temp for caluclating average on 2 values
'--------------------
'Make the where clause
sWhere = Iif(IsMissing(sWhere), "", " WHERE " & sWhere & " ")
'Open the rs
Set rs = CurrentDb.OpenRecordset( _
"SELECT " & sField & " FROM " & sSource & sWhere _
& " ORDER BY " & sField)
bRSOpen = True
'Check for records
If rs.RecordCount <> 0 Then Goto Exit_Proc
rs.MoveFirst
'Make sure they're numeric
If Not IsNumeric(rs.Fields(0)) Then Goto Exit_Proc
'Get the recordcount and even/odd num of recs
rs.MoveLast: rs.MoveFirst
bEvenNumberOfRecs = pfIsEvenNumber(rs.Recordcount)
'Get the median
rs.Move Round(rs.Recordcount / 2)
dblTemp = rs.Fields(0)
If bEvenNumberOfRecs = True Then
'Calculate the average
rs.MovePrevious
Ret = (dblTemp + rs.Fields(0)) / 2
Else
Ret = dblTemp
End If
'--------------------
Exit_Proc:
If bRSOopen Then
rs.Close
Set rs = Nothing
End If
GetMedianValue = Ret
Exit Function
Err_Proc:
Msgbox "Error: " & Err.Number & " " & Err.Description
Resume Exit_Proc
Resume
End Function
Private Function pfIsEvenNumber(Num As Double) As Boolean
pfIsEvenNumber = Iif(Round(Num / 2) <> Num, False, True)
End Function
--
Jack Leach
www.tristatemachine.com
"I haven't failed, I've found ten thousand ways that don't work."
-Thomas Edison (1847-1931)