Have autonumbered column restart value from 1 after primary key value changes?

喜你入骨 提交于 2020-01-07 02:16:20

问题


I have a 2 tables, call them PO and PO_LI. There is a column in PO called PO# which is a primary key, and is in a 1 to many relationship with the PO# column in PO_LI (the 1 being in PO). In PO_LI, the other columns are Line#, Description and LineAmount.

How can I reset the number back to 1 for every new PO #?
Can this be done while still using autonumber?
Can this be done in the ms-access gui or is VBA code required?


回答1:


You cannot manually edit an AutoNumber field or change its starting value. Your best bet is to maybe use VBA to get the max line number and increment it, and if you're using a new PO then you start at 1. You would put this VBA in the AfterUpdate event of the PO field.

You could do something like this:

Dim db as Database
Dim rec as Recordset
Dim rec2 as Recordset
Dim MyVal as Integer

Set db = CurrentDB
Set rec = db.OpenRecordset("Select LineNum from MyTable where PO = '" & Me.txtPO & "' group by PO")

'If there are no records returned, start at 1.  Otherwise, increment.
If rec.EOF = true then
  MyVal = 1
else
  Set rec = db.OpenRecordset("Select Max(LineNum) from MyTable where PO = '" & Me.txtPO & "'")
  MyVal = rec(0) + 1
endif

MyVal is now the number you will write to LineNum. Of course, you'll need to change the variables and such to be what's actually on your forms and in your tables, but you should get the idea.



来源:https://stackoverflow.com/questions/38308854/have-autonumbered-column-restart-value-from-1-after-primary-key-value-changes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!