' 生成单据编号 ' 参数: ' ruleName - 规则名称(如"生产报工单") ' departmentCode - 部门代码(如"01") ' monthValue - 日期值(支持日期/文本) ' dateFormat - 日期格式(如"yymm") ' prefix - 自定义前缀(如"BNZ") ' seqLength - 序列号位数(如4) ' 调用: ' If Nz(Me![Djbh]) = "" Then Me![Djbh] = GenerateDocumentNumber("生产外发合同编号", pinyin(Me.Ywdw), Me.Kdrq, "-yyyy-", "BNZ-", 4) BNZ-LXH-2025-0001 Function GenerateDocumentNumber( _ ruleName As String, _ departmentCode As String, _ monthValue As Variant, _ dateFormat As String, _ prefix As String, _ seqLength As Integer) As String On Error GoTo ErrorHandler Dim db As DAO.Database, rs As DAO.Recordset Dim formattedDate As String, sequence As Long ' 1. 日期处理与验证 If Not IsDate(monthValue) Then monthValue = Replace(Replace(CStr(monthValue), "年", "-"), "月", "") formattedDate = Format(CDate(monthValue), dateFormat) If Len(formattedDate) <> Len(dateFormat) Then GenerateDocumentNumber = "ERR:日期格式不匹配" Exit Function End If ' 2. 数据库操作 Set db = CurrentDb() Set rs = db.OpenRecordset( _ "SELECT TOP 1 * FROM Sys_AutoNumberRules " & _ "WHERE RuleName='" & Replace(ruleName, "'", "''") & "' " & _ "AND Prefixal='" & prefix & departmentCode & formattedDate & "'", _ dbOpenDynaset, dbPessimistic) ' 3. 安全获取序列号 If rs.EOF Then sequence = 1 Else ' 确保lastNo字段存在且足够长 If Len(rs!lastNo) >= seqLength Then sequence = Val(Right(rs!lastNo, seqLength)) + 1 Else sequence = 1 End If End If ' 4. 生成编号 GenerateDocumentNumber = prefix & departmentCode & formattedDate & _ Format(sequence, String(seqLength, "0")) ' 5. 更新记录 If rs.EOF Then rs.AddNew rs!ruleName = ruleName rs!prefixal = prefix & departmentCode & formattedDate rs!Digit = seqLength Else rs.Edit End If rs!lastNo = GenerateDocumentNumber rs.Upd