79733164

Date: 2025-08-12 12:22:28
Score: 0.5
Natty:
Report link

The reason you’re getting a syntax error is that Microsoft Access SQL does not allow ORDER BY or LIMIT clauses in an UPDATE statement.
Unlike some other SQL dialects (like MySQL or PostgreSQL), Access has a more limited syntax for updates. So, when you try to use ORDER BY TblTimeSheet.StartTime DESC and LIMIT 1 in your UPDATE query, Access throws a syntax error because those keywords aren’t supported there.


What you want to do:

You want to update only the latest record (the one with the most recent StartTime) for a particular employee, setting the EndTime to the current time (Now()).


How to fix this:

You can achieve this by using a subquery inside the WHERE clause that identifies the record with the maximum StartTime for that user. Here’s how you can write the query:

sql

CopyEdit

UPDATETblTimeSheet SET EndTime = Now() WHERE EmployeeUserName = 'sam.harper' AND StartTime = ( SELECT MAX(StartTime) FROM TblTimeSheet WHERE EmployeeUserName = 'sam.harper' );


Explanation:


Updated VBA code snippet:

vb

Dim strSQL As String Dim db As DAO.Database Set db = CurrentDb strSQL = "UPDATE TblTimeSheet " & _ "SET EndTime = Now() " & _ "WHERE EmployeeUserName = 'sam.harper' " & _ "AND StartTime = (SELECT MAX(StartTime) FROM TblTimeSheet WHERE EmployeeUserName = 'sam.harper');" db.Execute strSQL, dbFailOnError


A couple of tips:


Optional: Two-step approach if you want to be extra precise

You could first fetch the primary key of the last record in VBA, then update it specifically:

vba

Dim db As DAO.Database Dim rs As DAO.Recordset Dim lastRecordID As Long Dim strSQL As String Set db = CurrentDb ' Get the ID of the latest record for this user Set rs = db.OpenRecordset("SELECT TOP 1 ID FROM TblTimeSheet WHERE EmployeeUserName = 'sam.harper' ORDER BY StartTime DESC") If Not rs.EOF Then lastRecordID = rs!ID rs.Close ' Update the EndTime of that record strSQL = "UPDATE TblTimeSheet SET EndTime = Now() WHERE ID = " & lastRecordID db.Execute strSQL, dbFailOnError Else MsgBox "No records found for this user." End If

This method avoids any ambiguity if StartTime is not unique.

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: sambob_628