Avatar of Sanjay
SanjayFlag for United States of America

asked on 

vba code filtering top n values by group

So the coding below works if I use one make table query to make a table and then use a second select query that calls on the make table to find the top n values via the function defined below.  However, I am now trying to skip the making table part and use the criteria defined in the first select query (the query that made the table before) and use the second query that now queries on the first query to find the top N records by group.  The coding is working all the way til it faults out on the line:

 Set rs = rs2.OpenRecordset

where I get a query syntax error.  I did not have this problem before when querying the temp make table.  So I am assuming it has to do with the way I am filtering the recordset...........The coding below is not mine and was developed by an expert in prior postings.  Could use some help
Function Nth4000(GroupID, N)
    ' Returns the Nth Item in GroupID for use as a Top N per group
    ' query criteria.
    Static LastGroupId, LastNth4000InGroup
    Dim ItemName, GroupIDName, GDC, SearchTable
    Dim SQL As String, rs As DAO.Recordset, rs1 As DAO.Recordset, rs2 As DAO.Recordset, db As DAO.Database, qdf1 As DAO.QueryDef, qdf2 As DAO.QueryDef, prm As DAO.Parameter
    Dim qry1 As String
    Dim qry2 As String

    qry1 = "z nmdf servicedata_4000_a"
    qry2 = "z nmdf servicedata_4000_b"
    
    Set db = CurrentDb
    Set qdf1 = db.QueryDefs(qry1)
    Set qdf2 = db.QueryDefs(qry2)
    
    For Each prm In qdf1.Parameters
        prm.Value = Eval(prm.Name)
    Next prm
  
    Set rs1 = qdf1.OpenRecordset(dbOpenDynaset)

    If (LastGroupId = GroupID) Then
        ' Returned saved result if function is called with the
        ' same GroupID more than once in a row.
        Nth4000 = LastNth4000InGroup
    Else
        ' Set the SQL statement parameters. These are the only items
        ' that need to be customized in this function.
        ' Set to Item field name.
        ItemName = "Qty"
        ' Set to Group ID field name.
        GroupIDName = "PartNo1"
        ' GroupID Delimiter Character:
        ' For Text use "'" (Note that this is a quotation mark, a space,
        ' an apostrophe, a space, and then a quotation mark. The spaces
        ' are necessary for SQL statements), Date "#", Numeric ""
        GDC = "'"
        ' Set to search table.
        SearchTable = qry2
        ' Build a Top N SQL statement dynamically given N and
        ' GroupID as parameters. Note that the sort is by the
        ' item in descending order, in order to get the Top N
        ' largest items.
        SQL = "Select Top " & N & " [" & ItemName & "] "
        SQL = SQL & "From [" & SearchTable & "] "
        SQL = SQL & "Where [" & GroupIDName & "]=" & GDC & GroupID & GDC _
        & " "
        SQL = SQL & "Order By [" & ItemName & "] Desc"
        
        ' Open up recordset on Top N SQL statement and read the
        ' last record to get the smallest item in the Top N.
        Set db = CurrentDb()
        Set rs2 = qdf2.OpenRecordset
        rs2.filter = SQL
        Set rs = rs2.OpenRecordset
        
        If (rs.BOF And rs.EOF) Then
            ' No matches found, return a null.
            LastNth4000InGroup = Null
            LastGroupId = GroupID
            Nth4000 = LastNth4000InGroup
        Else
            ' Return the smallest Top N item in the group.
            rs.MoveLast
            LastNth4000InGroup = rs(ItemName)
            LastGroupId = GroupID
            Nth4000 = LastNth4000InGroup
        End If
        
    End If

End Function

Open in new window

Microsoft Access

Avatar of undefined
Last Comment
Sanjay
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

I have two parameters:  [Forms].[z filter].[BeginDate] and [Forms].[z filter].[EndDate] that are evaluated in qry1.
Avatar of Jeffrey Coachman
I can't say that I understand all you have going on there, but in just looking areound where you say the error occurs, ...
...It looks like you are not setting the Source (Table/Query/SQL) argument for the OpenRecordset Method


Set rs = rs2.OpenRecordset(?????)
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

Double click the query "z nmdf servicedata_4000_final_Method1" in the attached db...........

I am supposed to see the top 5 Qty values grouped by PartNo1
test.mdb
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

I cleaned up the coding behind the form for debug purposes so it does not get bothersome....................see attached.
test.mdb
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

The coding was taken from:

http://support.microsoft.com/kb/210039/en-us

I need "z nmdf servicedata_4000_a" select query to run first, then the "z nmdf servicedata_4000_b" select query, then "z nmdf servicedata_4000_final_Method1" select query that shows the top 5 Qty values grouped by PartNo1 based on the vba function
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

Hi:

Any thoughts so far......
ASKER CERTIFIED SOLUTION
Avatar of harfang
harfang
Flag of Switzerland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Sanjay
Sanjay
Flag of United States of America image

ASKER

Thx Harfang.  Your suggestion worked.
Microsoft Access
Microsoft Access

Microsoft Access is a rapid application development (RAD) relational database tool. Access can be used for both desktop and web-based applications, and uses VBA (Visual Basic for Applications) as its coding language.

226K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo