1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
Public Function MedianeDom(ByVal sExpression As String, ByVal sTable As String, _
Optional ByVal sCritere As String = vbNullString, Optional ByVal bNullAsZero As Boolean = False) As Variant
On Error GoTo MDErr
Dim oDb As DAO.Database
Dim oRs As DAO.Recordset
Dim sSql As String, sMsgErr As String
If Len(sExpression) = 0 Or InStr(1, sExpression, "*", vbBinaryCompare) > 0 Then
sMsgErr = "<Expression> ne peut être vide ou égal à '*'."
ElseIf InStr(1, sExpression, ",", vbBinaryCompare) > 0 Then
sMsgErr = "<Expression> ne doit pas retourner plus d'un champ."
ElseIf InStr(1, sExpression, " AS ", vbTextCompare) > 0 Then
sMsgErr = "Le champ de <Expression> ne doit pas être aliasé."
ElseIf Len(sTable) = 0 Then
sMsgErr = "<Table> ne peut être vide."
Else
sSql = "SELECT " & sExpression & " FROM " & sTable
If bNullAsZero = False Then
If Len(sCritere) > 0 Then
sCritere = sCritere & " AND NOT ISNULL(" & sExpression & ")"
Else
sCritere = "Not IsNull(" & sExpression & ")"
End If
End If
If Len(sCritere) > 0 Then
sSql = sSql & " WHERE " & sCritere
End If
sSql = sSql & " ORDER BY " & sExpression & ";"
Set oDb = CurrentDb
Set oRs = oDb.OpenRecordset(sSql, dbOpenSnapshot)
If oRs.EOF = False Then
Select Case oRs.Fields(0).Type
Case dbByte, dbInteger, dbLong, dbFloat, dbSingle, dbDouble
MedianeDom = CalcMedianeDom(oRs)
Case Else
sMsgErr = "<Expression> doit retourner un nombre."
End Select
End If
End If
If Len(sMsgErr) > 0 Then
MsgBox sMsgErr, vbExclamation, "MedianeDom"
End If
fin:
Set oRs = Nothing
Set oDb = Nothing
Exit Function
MDErr:
MsgBox "Erreur n°" & Err.Number & vbCrLf & "Description :" & Err.Description, vbExclamation, "MedianeDom"
Resume fin
End Function
Private Function CalcMedianeDom(oRs As DAO.Recordset) As Variant
Dim lCountEnr As Long
oRs.MoveLast
oRs.MoveFirst
lCountEnr = oRs.RecordCount
If lCountEnr > 1 Then
oRs.Move Int(lCountEnr / 2)
CalcMedianeDom = Nz(oRs.Fields(0))
If lCountEnr Mod 2 = 0 Then
oRs.MovePrevious
CalcMedianeDom = (CalcMedianeDom + Nz(oRs.Fields(0))) / 2
End If
Else
CalcMedianeDom = Nz(oRs.Fields(0))
End If
End Function |
Partager