|
先建一个模块 ContinuedIDOption Compare Database
Option ExplicitPrivate WithEvents DataForm As Form
Private strIDField As String
Private lngIDBegin As Long
Private lngIDStep As LongPublic Sub Init(srcForm As Form, srcField As String, Optional IDBegin As Long = 1, Optional IDStep As Long = 1)
Set DataForm = srcForm
DataForm.AfterInsert = "[Event Procedure]"
strIDField = srcField
lngIDBegin = IDBegin
lngIDStep = IDStep
End SubPrivate Sub DataForm_AfterInsert()
Dim daoRs As DAO.Recordset
Dim daoField As DAO.Field
Dim daoFieldName As Variant
Dim daoFieldNames As New Collection
Dim daoFieldValues As New Collection
Dim NewID As Long
Dim tmpID As Long
DataForm.Recordset.MoveLast
For Each daoField In DataForm.Recordset.Fields
daoFieldNames.Add daoField.Name
daoFieldValues.Add daoField.Value, daoField.Name
Next daoField
tmpID = lngIDBegin - lngIDStep
Set daoRs = CurrentDb.OpenRecordset("SELECT " & strIDField & " FROM " & DataForm.Recordset(strIDField).SourceTable, dbOpenDynaset, dbReadOnly)
Do Until daoRs.EOF
If daoRs(strIDField) > tmpID + lngIDStep Then Exit Do
tmpID = tmpID + lngIDStep
daoRs.MoveNext
Loop
daoRs.Close
Set daoRs = Nothing
NewID = tmpID + lngIDStep
If NewID >= DataForm.Recordset(strIDField) Then
NewID = DataForm.Recordset(strIDField)
GoTo Check_Next
End If
DataForm.Recordset.Delete
DataForm.Recordset.AddNew
For Each daoFieldName In daoFieldNames
DataForm.Recordset(daoFieldName) = daoFieldValues(daoFieldName)
Next daoFieldName
DataForm.Recordset(strIDField) = NewID
DataForm.Recordset.Update
'设定下个默认值
Check_Next:
tmpID = lngIDBegin - lngIDStep
Set daoRs = CurrentDb.OpenRecordset("SELECT " & strIDField & " FROM " & DataForm.Recordset(strIDField).SourceTable, dbOpenDynaset, dbReadOnly)
Do Until daoRs.EOF
If daoRs(strIDField) > tmpID + lngIDStep Then Exit Do
tmpID = tmpID + lngIDStep
daoRs.MoveNext
Loop
daoRs.Close
Set daoRs = Nothing
If tmpID = NewID Then Exit Sub
DataForm.Recordset.FindFirst strIDField & "=" & tmpID
For Each daoField In DataForm.Recordset.Fields
daoFieldValues.Remove daoField.Name
daoFieldValues.Add daoField.Value, daoField.Name
Next daoField
DataForm.Recordset.Delete
DataForm.Recordset.AddNew
For Each daoFieldName In daoFieldNames
DataForm.Recordset(daoFieldName) = daoFieldValues(daoFieldName)
Next daoFieldName
DataForm.Recordset.Update
End Sub窗体代码Option Compare Database
Option ExplicitPublic CID As New ContinuedIDPrivate Sub Form_Load()
CID.Init Me, "id"
End Sub
试一试,应该没有问题.
|
|