I am new to VBA code so I may have not taken the most practical of approaches on the following situation. I have Items
that is a subform to Purchase_Orders
. One of the fields in Items
is PO_Line_item
. This has to be a sequence of numbers (from 1) where PO_ID is the same. If several items have the same PO_ID have then I need this sequence. I cannot use the Item_ID as they may not always be added in succession.
here's the code I used:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim db As Database
Dim rs As DAO.Recordset
Dim currentItem As String
Dim seq As Long
Dim sql As String
sql = "SELECT * " & _
"FROM Items " & _
"WHERE PO_ID = " & Me.Parent.PO_ID
Set db = CurrentDb
Set rs = db.OpenRecordset(sql, dbOpenDynaset)
rs.MoveFirst
currentItem = ""
With rs
Do While Not .EOF
If currentItem = "" Then
seq = 1
currentItem = seq
Else
seq = currentItem + 1
currentItem = seq
End If
Me.PO_Line_Item = seq
.MoveNext
Loop
End With
Set rs = Nothing
Set db = Nothing
End Sub
This works great if I stay on the record, I get items 1 then 2 then 3. however if I return the form and input another item record then I get a repeat of the last PO_Line_Item
. ie 1,2,3,(return to form)3,4.
If anyone knows why this is happening, or if there is an alternative method that I can use that will work as well; then ideas are welcome. Thanks in advance.
You don't need a recordset loop to find the number of elements - use SQL COUNT() instead.
sql = "SELECT COUNT(*) " & _
"FROM Items " & _
"WHERE PO_ID = " & Me.Parent.PO_ID
Or even shorter with the Access DCount function:
' Number of existing records (may be 0)
seq = DCount("Item_ID", "Items", "PO_ID = " & Me.Parent.PO_ID)
' assign the next number
Me.PO_Line_Item = seq + 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.