我正在尝试在表单保存时(插入前)将新员工插入带有自定义ID字段的表中。要创建自定义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表单事件中保存新条目时,它会不断给出我的错误。
使用我的最终解决方案进行更新,我不得不进行修改,因为对格式化为数字非常挑剔。感谢你们两位的帮助!
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
答案 0 :(得分:0)
获取与名称匹配的最大员工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
答案 1 :(得分:0)
根据安德烈建议使用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