Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select Top n records

Status
Not open for further replies.

tamus121

Technical User
Mar 19, 2007
38
GB
Hi, hope someone can help.
I have a access report which has a query as the record source. This selects the top 6 records from a table using "SELECT TOP 6". I would like to have a text box on a form for the user to enter a variable amount of records to be listed. I can't get this to work if I change the "6" to the text box name. Is this even possible?
tamus
 
This will not work as you want it to. You can use some DAO code to update the SQL property of a saved query.

Code:
   Currentdb.QUeryDefs("YourQueryName").SQL = "SELECT TOP " _
    & Me.txtTop & " * FROM qselYourQUery ORDER BY 1,2"

Duane
Hook'D on Access
MS Access MVP
 
Thanks Duane for your reply
Am I correct in thinking that I would need to create a new query and make it the record source of my report. Then use the code to update the new query before I preview the report?
tamus
 
Supposing you have Access 2003, you could build the SQL in the calling form, then pass it to the OpenArgs property of the report:

Private Sub CmdButton_Click()
Dim strSQL As String
strSQL="Select Top " & me.txtTop & " From YourQueryName"
DoCmd.OpenReport "ReportName",,,,,strSQL
End Sub


Then set the recordsource in the Open event:

Private Report_Open(Cancel As Integer)
Me.Recordsource=Me.OpenArgs
End Sub

[pipe]
Daniel Vlas
Systems Consultant

 
Thanks for your replies

I have used the OpenArgs property as suggested by danvlas and it works although I had to place a * before FROM to get it to work. Not sure what it does!
tamus
 
I forgot to type it :)

It returns ALL fields from the source. My advice is to avoid using it and replace it with the exact list of the fields you really need.

So... instead of
Select Top 100 * From TableOrQuery

I would use
Select Top 100 [Field1Name], [Field2Name]...,[FieldXName]
From TableOrQuery




[pipe]
Daniel Vlas
Systems Consultant

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top