【问题标题】:Access DB - Get last index numberAccess DB - 获取最后一个索引号
【发布时间】:2020-07-13 18:53:49
【问题描述】:

我正在尝试在保存表单时(插入前)将新员工插入具有自定义 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 表单事件中保存新条目时,它不断给我 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

【问题讨论】:

    标签: ms-access vba ms-access-2010


    【解决方案1】:

    按照安德烈使用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
    

    【讨论】:

    • 我已经编辑了原始问题,因为我在尝试保存表单时无法使用建议的功能更改。
    • 我已经尝试了这两个建议,并在表单的 BeforeInsert 和 BeforeUpdate 事件中调用了该函数。当我尝试在 BeforeInsert 上输入新的名字和姓氏时出现“无效使用 Null”,当我尝试保存时在 BeforeUpdate 上出现“索引或主键不能包含空值”。
    【解决方案2】:

    获取与姓名匹配的最大员工 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
    

    【讨论】:

    • 然后在必要时使用前导零作为前缀,使用Right("0" & nSEQ,2)
    • 这可能是我工作所需要的,但是当我在 Form_BeforeInsert 事件上使用 Me.EMPLOYEE_ID = EmployeeNumber.GetNextEmployeeId(Me.LAST_NAME, Me.FIRST_NAME) 时,当我单击保存时给我一个警告,索引或主键不能为空。我会调用哪个事件,以便在保存之前使用函数 GetNextEmployeeId?
    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2011-05-07
    • 2013-10-27
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多