Trying to lookup last record

SteveL13 used Ask the Experts™
What is wrong with this code that I'm using in an oncurrent event of a form?

Me.txtLastTranxItem = DLast("[PartN]", "tblWarehouseTransTranx", "[PartN] = " & Forms![frmWHtransTranx]![cboPartN])

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2013
Me.txtLastTranxItem = "" & DLookup("[PartN]", "tblWarehouseTransTranx", "[YourAutonumberfield] = " & DMax("YourAutonumberfield","tblWarehouseTransTranx"))

Open in new window

This is one method to get the last record -- but may not be reliable when multiple users are adding to the same table at the same time.

The structure of the DLast call you've stated looks OK; are you sure that the value you want returned is PartN, when you are already specifying PartN in the criterion of the DLookup?  It's like you are looking up a value you already know (unless PartN is a similar value in a different table of course).

The only other thing I can think of off the top of my head is the value in the criterion "[PartN] = " & Forms![frmWHtransTranx]![cboPartN].  I presume from your syntax that the values in your combo box cboPartN are numbers as opposed to strings.  If you had string values, you'd need to enclose the criterion value in single quotes, i.e.
"[PartN] = '" & Forms![frmWHtransTranx]![cboPartN] & "'"

Jeffrey CoachmanMIS Liason
Most Valuable Expert 2012

DLast, (like most other aggregate functions), will depend on how the table is sorted.
Remember a user may be able to easily change how a table is sorted

This is why it may be better to create a query (of the same table) that is sorted the way you want.
Then DLast *should* return the correct value.

However to be more certain, use something like what mbizup posted.

...or create a date/time stamp field with a default value of: =Now()
But even here you may have to make a distinction between Last "added" record, and last "edited" record.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial