Hi Katie!
This is probably not the most elegant way of doing this - but since you've got your numeric values mixed in with the first 3 of your Student Surname in your StudentID field . . . this is what I came up with.
If you had your numeric ID in a separate field, you could use the DMAX() function in your After Update procedure and not have to mess with slightly more complex VBA . . .
Still . . . give this a shot.
1. Create a New Module.
2 Type in Option Explicit on top and then paste this function in there:
Code:
Function Highest_ID() As Integer
'Declare Variables:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL, strStudentID As String
Dim intHighID, intID As Integer
'If there is an error - go to the error handling routine at bottom.
On Error GoTo Error_Handle
'Set/initialize variables:
Set db = CurrentDb
strSQL = "Select * From [tbl_StudentDetails]"
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
intHighID = 0
With rs
'This Do While loop goes through all the records in strSQL.
Do While Not rs.EOF
'Get the 4-digit value from current StudentID and convert it to an integer.
strStudentID = rs![StudentID]
intID = CInt(Right(strStudentID, 4))
'If the number in the current record is the higher than the previous one - then make this the 'High ID'.
If intID > intHighID Then
intHighID = intID
End If
.MoveNext 'Move to next record in recordset.
Loop 'Back to 'Do While' to check if we are at the end of the file.
'This returns the highest existing numeric value to the calling routine.
Highest_ID = intHighID
Exit_Get_DB_Values:
If Not rs Is Nothing Then
rs.Close
Set rs = Nothing
End If
Set db = Nothing
Exit Function
Error_Handle:
Resume Exit_Get_DB_Values
End With
End Function
3. Select the StudentSurname text box, click in the Property Sheet - Event - After Update row - [...].
4. When prompted - choose 'Code Builder'.
5. Paste this between the Private Sub StudentSurname_AfterUpdate() . . . and the End Sub lines:
Code:
Dim intNewID As Integer
intNewID = Highest_ID + 1
Me.StudentID = Left(StudentSurname, 3) & intNewID
Now . . . when you create a new record and tab off the StudentSurname field after typing in the new surname, you will see the StudentID for the new entry appear in the StudentID field on the Form.
Let us know if you have any problems.
All the best!!