由于您的 Tracking Number 是标准格式并用 0 填充,因此应该很容易获取每个给定年份的最后一个,拆分两部分,增加序列部分,然后返回下一个。
我会这样做。
将其粘贴到新模块中。 (请务必将 MainTable 更改为您的主表的名称,并将 TRACKING_NO 更改为您的跟踪号列名称)
Function GetNextTrackingNo(Optional nYear As Long = 0) As String 'be sure to pass nYear as 2 digit year if you ever use that option!
Dim strLastTN As String 'get the last tracking number per given year
Dim nSEQ As Long
If nYear = 0 Then nYear = Year(Now) - 2000 'year was not passed so use current year; -2000 should be fine until year 2100
'Get the last Tracking number for the given year
strLastTN = Nz(DMax("TRACKING_NO", "MainTable", "Left([TRACKING_NO],2) = '" & nYear & "'"), 0)
'get the sequence number from the string
nSEQ = CLng(Right(strLastTN, 4))
'increment the sequence so you get the next one.
nSEQ = nSEQ + 1
'you might want to have a check here to see if next sequence is greater than 9999!
'return the next tracking number in the desired format
GetNextTrackingNo = Format(nYear, "00") & "-" & Format(nSEQ, "0000")
End Function
你可以在另一个函数中测试它:
Function TestGetNextTrackingNo()
MsgBox GetNextTrackingNo 'show the next tracking number for this year
MsgBox GetNextTrackingNo(14) ' show the next tracking number for last year
MsgBox GetNextTrackingNo(16) 'show next tracking number for next year
End Function
您可以使用 Form_BeforeInsert 在表单中使用该功能(将 TRACKING_NO 更改为您的跟踪号列名称)
Private Sub Form_BeforeInsert(Cancel As Integer)
Me.TRACKING_NO = GetNextTrackingNo
End Sub
或者如果您想在当前记录中使用日期字段来指定年份,请使用:
Private Sub Form_BeforeInsert(Cancel As Integer)
Me.TRACKING_NO = GetNextTrackingNo Year(me.MyDateControl)-2000
End Sub