After reading this thread, following the advice of others, and poking around
the KB, I came up with the code below your question. At the risk of showing
glaring inefficiences to the experts, I'm sharing it as a gesture of
appreciation for the help I've found here.
There's probably a better way, but it works for me. Hope it is helpful for
you.
Keith said:
I have a client who would like to have serial numbers assigned to records as
follows:
05-0001
05-0002
where the "05" indicates the year, and the "0001" indicates the record
number (incrementing by 1) within a given year. In other words, next year,
the first serial number would be:
06-0001
etc.
The dash could be optional, as I could always format the field to
incorporate that. Does anyone have an idea as to how I can accomplish this?
I think coding something in the data entry form makes the most sense, but I'm
not quite sure how.
Thanks,
Keith
Public Function NextCustomCounter(TableName As String) As String
On Error GoTo NextCustomCounterErr
Dim rs As DAO.Recordset
Dim LastCounter As String
Dim NextCounter As String
Dim intCount As Integer
Set rs = CurrentDb.OpenRecordset("tblCustomCounters", 2)
'Open the DAO recordset.
With rs
.FindFirst "TableName = '" & TableName & "'"
If Not .nomatch Then 'When the table is found,
If Not IsNull(!LastCounter) Then 'And a counter entry
exists
'Check to see if it's a new year
If Left(!LastCounter, 2) = Format(Date, "yy") Then
'Use the next sequental counter
LastCounter = !LastCounter
Else
'If this is the first transaction of the new year, reset
the counter
LastCounter = Format(Date, "yy") & "-0"
End If
Else
LastCounter = Format(Date, "yy") & "-0"
End If 'Counter exists
'Update the record with the next entry
.Edit
Else
'Add the new table & counter to the CustomCounters table
LastCounter = Format(Date, "yy") & "-0"
.AddNew
!TableName = TableName
End If
'Increments by one the value of the numeric portion of the counter
'Determines the length of the string by subtracting 3 (YY-)
intCount = Val(Right(LastCounter, (Len(LastCounter) - 3))) + 1
'Formats the updated value of the counter
NextCounter = Format(Date, "yy") & "-" & CStr(intCount)
'Store the counter
!LastCounter = NextCounter
.Update
End With 'recordset
'Clear the recordset
Set rs = Nothing
'Sets for return to the calling code
NextCustomCounter = NextCounter
Exit Function
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'The following error routine should be replaced with a custom
'error routine.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
NextCustomCounterErr:
MsgBox "Error " & Err & ": " & Error$
'If Err <> 0 Then Resume
'End
End Function