First of all, you need a field that identifies the category. From this, there must be a way of determining your three-character stub.
You would also need a form to enter this data in. For simplicity we'll start with a form that has the three simple controls - [txtCode], [txtCategory] & [txtProduct].
Now, an important point is that you cannot guarantee the value of the code until it has been saved. We can create a
DefaultValue for the control if you like, but this may not reflect the actual value used, so you may prefer not to set a default at all. Your choice.
The important code, that can be run to set the
DefaultValue, but must be run from within
Form_BeforeInsert, will determine the correct value at that specific point in time using the category from [txtCategory].
This code will use
DMax() to find the max numerical value attached to any record of the matching category. It will take this value, or 0 if no value found, then add 1 to it and append it to the category stub to form the new [txtCode].
- Private Sub Form_BeforeInsert(Cancel As Integer)
-
If IsNull(Me.txtCategory) Then
-
Call MsgBox("No Category selected")
-
Cancel = True
-
Exit Sub
-
End If
-
Me.txtCode = NextCode(Me.txtCategory)
-
End Sub
-
-
Private Function NextCode(strCategory as String) As String
-
Dim intMax As Integer
-
-
intMax = Val(Right(Nz(DMax("[code]", _
-
"[ProdTable]", _
-
"[Category]='" & Me.strCategory & "'"), 0), 4))
-
NextCode = UCase(Left(strCategory, 3)) & "-" & Format(intMax + 1, "0000")
-
End Function