The down side of this approach is that if you are working in an environment
where more than one person could be using the database at the same time, then
you could end up with duplicates. The reason for this is that the
[KeyFieldName] field will not actually get updated until you save the current
record, so if one person creates a new record, and is working on it but has
not saved it, and another person creates a record, they will end up with the
same #.
One way to handle this is to not assign the number until the user saves the
record (in the forms BeforeUpdate event).
Another method is to store the number in a table (I use tbl_db_Parameters
which only contains 1 record) and then create a function that opens that
table, gets the current value from the appropriate field in that table, and
increments the value in the table. Something like:
Public Function fnNextKey(KeyName as string) as long
Dim strSQL as string
Dim rs as DAO.Recordset
strSQL = "SELECT [" & KeyName & "] FROM tbl_db_Parameters"
set rs = currentdb.OpenRecordset(strsql,,dbFailOnError)
with rs
.edit
fnNextKey = rs(KeyName)
rs(KeyName) = rs(KeyName) + 1
.update
end with
rs.close
set rs = nothing
End Function
----
HTH
Dale
BruceM via AccessMonster.com said:
To expand on the other response, as the Default Value of a text box bound to
the key field:
=Nz(DMax("[KeyFieldName]","[tblName]"),0) + 1
The Nz is necessary only for the first record. If you already have values in
that field you will not need it, in which case it would be:
=DMax("[KeyFieldName]","[tblName]") + 1
Also, if you do use the expression with Nz you can use a number other than 0.
If your first record is to be numbered 202000, substitute 201999 for the 0.
Again, this is only if there are no records with a value in that field when
you begin.
You can hide that text box, then set Control Source of an unbound text box:
If the "C-" prefix is not a constant, please provide details.
- Show quoted text -