1
ห้อง MS Access / : สอบถามการใช้ Auto Number ครับ
« เมื่อ: 27 มิ.ย. 62 , 12:39:20 »
โค้ดแบบสั้นๆ ง่ายๆ ตามไฟล์แนบครับ
โพสต์นี้ได้รับคำขอบคุณจาก: Nick_1234
This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Const MaxRec = 26
Dim DB As DAO.Database
Dim RS As DAO.Recordset
Dim MaxDTStr As String ' วันเวลาล่าสุดของกลุ่มเรคอร์ด (แต่เป็น string เพื่อลดความยาวของโค้ด)
Dim MaxA As Long ' ค่าสูงสุดของ A ในกลุ่มเรคอร์ดล่าสุด
Dim NeedA As Boolean ' TRUE = ระบบต้องการค่า A บนฟอร์ม
NeedA = False
Set DB = CurrentDb
Set RS = DB.OpenRecordset("select max(DT) as MaxDT from TB")
If IsNull(RS!MaxDT) Then
NeedA = True
Else
' #2.2
MaxDTStr = Format$(RS!MaxDT, "dd/mmm/yyyy hh:nn:ss")
Set RS = DB.OpenRecordset("select count(*) as N from TB where DT = #" & MaxDTStr & "#")
If RS!N = 0 Or RS!N >= MaxRec Then NeedA = True
End If
If NeedA Then
' #3.1
If Nz(Me.A, 0) = 0 Then
MsgBox "ป้อน A ด้วย"
Me.A.SetFocus
Cancel = True: Exit Sub
End If
If Not DB.OpenRecordset("select A from TB where A = " & CStr(Me.A)).EOF Then ' #4.1
MsgBox "A ซ้ำของเดิม"
Me.A.SetFocus
Cancel = True: Exit Sub
End If
Me.DT = Now() ' #2.1
Else
' #3.2
Me.A = DB.OpenRecordset("select max(A) as MaxA from TB where DT = #" & MaxDTStr & "#")!MaxA
Do
Me.A = Me.A + 1
Loop Until DB.OpenRecordset("select A from TB where A = " & CStr(Me.A)).EOF ' #4.2
Me.DT = CDate(MaxDTStr) ' #2.2
End If
End Sub