FoxProProgrammer
Programmer
I wrote a function that calculates the Median of a set of data. Here is the code.
The function works as long as tblname is a Table. I want to use the function in cases where tblname is a Query. Can this be done? It doesn't seem like it should matter if the the data comes from a Table or Query. I get "run time error 3061, Too few parameters. Expected 2" when tblname is a Query output. It works fine when tblname is a Table. Effectively I've got a subquery in the From Clause. If this is the problem, how can I get this done? Should I use a make table query instead, and pass the name of the table that got created to my Median function? I want to avoid that if possible.
Thanks,
dz
dzaccess@yahoo.com
Code:
Option Compare Database
Public Function Median(fldname As String, tblname As String)
Dim strQuery As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim numRecs, dataPt As Integer
' Get the data and sort it.
strQuery = "Select [" & fldname & "] From [" & tblname & "] Order by [" & fldname & "];"
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery, dbOpenDynaset, dbReadOnly)
' Count the number of records and move to the beginning of record set.
numRecs = rs.RecordCount
rs.MoveFirst
' Find the Median
dataPt = Int((numRecs + 1) / 2)
If dataPt Mod 2 = 0 Then
' Odd number of records.
rs.Move (dataPt - 1)
Median = rs.Fields(fldname)
Else
' Even number of records. Average the middle two values.
rs.Move (dataPt - 1)
Median = rs.Fields(fldname)
rs.MoveNext
Median = (Median + rs.Fields(fldname)) / 2
End If
End Function
The function works as long as tblname is a Table. I want to use the function in cases where tblname is a Query. Can this be done? It doesn't seem like it should matter if the the data comes from a Table or Query. I get "run time error 3061, Too few parameters. Expected 2" when tblname is a Query output. It works fine when tblname is a Table. Effectively I've got a subquery in the From Clause. If this is the problem, how can I get this done? Should I use a make table query instead, and pass the name of the table that got created to my Median function? I want to avoid that if possible.
Thanks,
dz
dzaccess@yahoo.com