Access DB - 获取最后的索引号

Access DB - Get last index number

我正在尝试在保存表单时(插入前)将新员工插入到带有自定义 ID 字段的 table 中。要创建自定义 ID,我使用姓氏的前 4 个字母和名字的前 2 个数字,后跟由匹配的员工姓名数生成的 2 位数字:

John Smith = SMITJO01 (first entry)
John Smith = SMITJO02 (second John Smith)

但是,我不知道如何根据列表中有多少其他匹配名称将唯一索引 (01, 02) 添加到函数中:

Function GetNextEmployeeId(ByVal lastName As String, ByVal firstName As String) As String

    Dim strNameComp As String
    Dim nSEQ As Long

    strNameComp = Left(lastName, 4) & Left(firstName, 2)

End Function

编辑: 由于 EMPLOYEE_ID 是主键,因此当我尝试保存新条目时,在 BeforeUpdate 和 BeforeInsert 表单事件中,它一直给我 Null 错误。

更新我的最终解决方案,我不得不修改,因为它对格式化为数字很挑剔。感谢你们两位的帮助!

Function GetNextEmployeeId(ByVal lastName As String, ByVal firstName As String) As String

    Dim strNameComp As String
    'Dim varMax As Var
    Dim nSEQ As Long

    strNameComp = UCase(Left(lastName, 4)) & UCase(Left(firstName, 2))

    varMax = DMax("EMPLOYEE_ID", "EMPLOYEES", "EMPLOYEE_ID LIKE '" & strNameComp & "*'")

    If IsNull(varMax) Then
        ' no one there yet
        nSEQ = 1
    Else
        ' split off the number part, convert to number, add 1
        nSEQ = Val(Right$(varMax, 2)) + 1
    End If

    GetNextEmployeeId = UCase(strNameComp) & Format(nSEQ, "00")

End Function

获取最多个与姓名匹配的员工ID:

varMax = DMax("EmployeeId", "tblEmployee", "EmployeeId LIKE '" & strNameComp & "*'")

然后你需要区分一下:

If IsNull(varMax) Then
    ' no one there yet
    nSEQ = 1
Else
    ' split off the number part, convert to number, add 1
    nSEQ = Val(Right$(varMax, 2)) + 1
End If

按照 Andre 关于使用 DMax 的建议,尝试这样的操作:

Function GetNextEmployeeId(ByVal lastName As String, ByVal firstName As String) As String
    Dim strPre As String
    Dim varMax As String

    strPre = Left(lastName, 4) & Left(firstName, 2)
    varMax = DMax("EmployeeId", "tblEmployee", "EmployeeId LIKE '" & strPre & "*'")

    GetNextEmployeeId = strPre & Right("0" & Right(Nz(varMax, "0"), 2) + 1, 2)
End Function