Access 2010 - display last ID (auto number)

gawai

New Member
Joined
Mar 1, 2014
Messages
15
hi,
i want to display last ID in my form field, below code does not work. any solution ?

Private Sub Form_Load()
Dim db As Database
Dim rs As DAO.Recordset


Set db = CurrentDb()
selectQuery = "SELECT ID FROM myTable"
Set rs = CurrentDb.OpenRecordset(selectQuery)


rs.MoveLast
lastRec = rs("ID")



Me.fldRptNo.Value = lastRec
MsgBox lastRec




'get newly inserted record ID (autonumber)
'rs.Move 0, rs.LastModified
'newID = rs("ID")


rs.Close
Set rs = Nothing


End Sub
 

Excel Facts

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.
Does the message box come up with the value but it just doesn't populate the textbox?
 
Upvote 0
Try this.

Code:
Private Sub Form_Load()
    Dim db As Database
    Dim rs As DAO.Recordset




    Set db = CurrentDb()
    selectQuery = "SELECT max(ID) as ID FROM myTable"
    Set rs = CurrentDb.OpenRecordset(selectQuery)




    rs.MoveLast
    lastRec = rs!ID
    Me.fldRptNo.Value = lastRec
    MsgBox lastRec
    rs.Close
    Set rs = Nothing




End Sub
 
Upvote 0
thanks.
it works but after i changed to :

Set db = CurrentDb()
selectQuery = "SELECT max(ID) as lastID FROM TblHT"
Set rs = CurrentDb.OpenRecordset(selectQuery)


rs.MoveLast
lastRec = rs!lastID
Me.fldRptNo.Value = lastRec
MsgBox lastRec
 
Upvote 0
Out of curiosity in your original code did you change myTable to TblHT?
 
Upvote 0
Not really but ID was repeated in your sql stmt.
I changed to lastID

SELECT max(ID) as lastID
Instead of
SELECT max(ID) as ID
 
Upvote 0
Yeah I get that, I'm just saying your original errors may have been due to you not referencing the table name correctly if you hadn't changed myTable to TblHT.
 
Upvote 0

Forum statistics

Threads
1,215,226
Messages
6,123,734
Members
449,116
Latest member
alexlomt

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top