Results 1 to 2 of 2
  1. #1
    afa is offline Novice
    Windows 8 Access 2013
    Join Date
    Feb 2016
    Posts
    22

    How do I delete the last record in a table?

    How can I delete only the last record in a table? All entries are assigned an Autonumber ID.
    I got as close as using this code. How do I point to the particular table?
    DoCmd.GoToRecord , , acLast
    docmd.RunCommand acCmdDeleteRecord

  2. #2
    ssanfu is offline Master of Nothing
    Windows XP Access 2010 32bit
    Join Date
    Sep 2010
    Location
    Anchorage, Alaska, USA
    Posts
    9,664
    "Last" is a relative term. It implies that there is an order to the dataset. The problem is that a table has no order. A table is a "bit bucket". It might look like there is an order, but the next time you open the table, the records can be in a completely different "order".

    If you say "I want to delete the record with the highest (maximum) ID", that can be done.

    You could use: DMax() or a recordset to get the maximum ID number, then use a delete query to delete the record.

    Code:
    Dim lngMax as Long
    lngMax = DMax("ID", "YourTable")
    CurrentdB.Execute "DELETE * FROM YourTable WHERE ID = " & lngMax, dbFailOnError
    or

    Code:
    Public Sub DeleteLastRec()
        Dim sSQL As String
        Dim r As DAO.Recordset
        Dim lngMax As Long
    
        'use a query to get max value from table
        sSQL = "SELECT TOP 1 Max(ID) FROM YourTable ORDER BY ID Desc"
        Set r = CurrentDb.OpenRecordset(sSQL)
    
        lngMax = r("ID")
        r.Close
        Set r = Nothing
    
        'Delete the record
        sSQL = "DELETE * FROM YourTable WHERE ID = " & lngMax
    
        CurrentDb.Execute sSQL, dbFailOnError
    
    End Sub

Please reply to this thread with any new information or opinions.

Similar Threads

  1. Delete FIRST record from a table.
    By anupludra in forum Access
    Replies: 4
    Last Post: 03-17-2015, 06:44 PM
  2. Replies: 1
    Last Post: 10-10-2014, 05:58 AM
  3. Table shows deleted record but it won't delete
    By khughes46 in forum Access
    Replies: 3
    Last Post: 09-19-2014, 09:35 AM
  4. Replies: 1
    Last Post: 10-22-2013, 06:48 AM
  5. delete table record with VBA
    By msasan1367 in forum Access
    Replies: 6
    Last Post: 07-07-2013, 11:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums