Median in Report

J

Jason

Hi,

I'm trying to use the example code from Microsoft's knowledge base to
calculate the median in a report (code below). The code works fine for me in
calculating the the median of the entire dataset of my table/query. The
problem I run into is when I try to calculate the same median function in a
report on a grouping, instead of returning the median for that specific
grouping, it returns the median for the entire dataset repeatedly under each
grouping.

As an example, my report is grouped based on Industry, and I would like to
return the median calculation of revenues as outlined below. In this case,
I have input the following formula in the textbox in the Industry Footer
section of the report: =Median("qry_Industry","Revenues")

Industry 1

Company1 $100
Company2 $180
Company3 $300
Company4 $450
Company5 $500
Median $300

Industry 2

Company6 $180
Company7 $250
Company8 $375
Median $250

Data as presented above represents my desired output, however, what I am
currently getting returned is the median for the entire set of inputs ($275,
which represents the median of all 8 Companies), which is being returned as
the median for both Industry1 and Industry2. Can someone suggest how I might
alter the code below or possibly provide other coding that would handle this?
Thanks.

Function Median(tName As String, fldName As String) As Single
Dim MedianDB As DAO.Database
Dim ssMedian As DAO.Recordset
Dim RCount As Integer, i As Integer, x As Double, y As Double, _
OffSet As Integer
Set MedianDB = CurrentDb()
Set ssMedian = MedianDB.OpenRecordset("SELECT [" & fldName & _
"] FROM [" & tName & "] WHERE [" & fldName & _
"] IS NOT NULL ORDER BY [" & fldName & "];")
'NOTE: To include nulls when calculating the median value, omit
'WHERE [" & fldName & "] IS NOT NULL from the example.
ssMedian.MoveLast
RCount% = ssMedian.RecordCount
x = RCount Mod 2
If x <> 0 Then
OffSet = ((RCount + 1) / 2) - 2
For i% = 0 To OffSet
ssMedian.MovePrevious
Next i
Median = ssMedian(fldName)
Else
OffSet = (RCount / 2) - 2
For i = 0 To OffSet
ssMedian.MovePrevious
Next i
x = ssMedian(fldName)
ssMedian.MovePrevious
y = ssMedian(fldName)
Median = (x + y) / 2
End If
If Not ssMedian Is Nothing Then
ssMedian.Close
Set ssMedian = Nothing
End If
Set MedianDB = Nothing
End Function
 
K

Klatuu

You need to filter the recordset based on what is in the current group. That
is, you are grouping by a specific field. The value of the field is most
likely in a control in the group footer. Use the value of that control to
filter the recordset.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top