First, Last Functions

First, Last Functions

In Microsoft Access, you can use the First and Last functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the First and Last functions in a calculated control on a form or report.

The First and Last functions are most useful in calculated controls on a report. For example, if you have an Order report that is grouped on a ShipCountry field and sorted on an OrderDate field, you can use the First and Last functions in calculated controls to show the range of earliest to latest order dates for each grouping. To group on the ShipCountry field, click Sorting And Grouping on the Report Design toolbar. Choose ShipCountry in the Field/Expression column, and set the GroupHeader and GroupFooter properties to Yes. In Design view, create two new text boxes in the ShipCountry footer, and set the ControlSource property for both to the following expressions:

=First([OrderDate])
=Last([OrderDate])

When you switch to Print Preview, you will see the first and last order dates for each group of orders.

Notes   If you want to return the first or last record in a set of records in Access 2000, you should create a query sorted as either ascending or descending and set the TopValues property to 1. For more information, see the TopValues property topic. From Visual Basic, you can also create a sorted result set of the query, and use the DAO MoveFirst or MoveLast method to return the first or last record in a set of records.

In Access projects (.adp), the First and Last functions operate as if the underlyng information is not sorted. The function will return the first entry that matches the criteria listed in the function which may not be the first or last matching entry in the underlying information.