Function StandardDeviation(ByVal strTable As String, ByVal strField As String) As Double
On Error Goto Err_StandardDeviation
' Author: Mile-O-Phile
' History: 25-Feb-2003 - Initially written
' Inputs: tablename (strTable) - the recordset upon which the
' function will take its range of samples from
' fieldname (strField) - the field in the recordset (strTable)
' from which the Standard Deviation will be calculated
' Process: calculates two main parts of the Standard Deviation
' formula which would have been difficult to do without
' a pre-defined formula
' using the values determined from the first process
' the two variables (dblSquareTotal and dblTotal) are
' used in the Standard Deviation formula to produce
' the final output
' Output: the Standard Deviation
' Notes: This function will only work where the source data
' being referred to is held within a recordset ad can not
' calculate the Standard Deviation if the sample data is
' held within an array.
' set up a recordset to navigate through
Dim db As Database, rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset(strTable)
' move to the first record in our recordset
rs.MoveFirst
' dimension some variables
Dim intCounter As Integer, dblSquareTotal As Double, dblTotal As Double
' do the sum part of the function by going through the records
' rather than use the aggregate
' functions as with numerous records it would be too slow
For intCounter = 1 To rs.RecordCount
dblSquareTotal = dblSquareTotal + (rs.Fields(strField) * rs.Fields(strField))
dblTotal = dblTotal + rs.Fields(strField)
rs.MoveNext
Next intCounter
' calculate the standard deviation
StandardDeviation = Sqr(((rs.RecordCount * dblSquareTotal) - (dblTotal * dblTotal)) / (rs.RecordCount * (rs.RecordCount - 1)))
' finally, close the recordset
rs.Close
Exit_StandardDeviation:
Exit Function
Err_StandardDeviation:
MsgBox Err.Description, vbCritical, "Error number " & Err.Number & " has occurred."
Resume Exit_StandardDeviation
End Function