John Fanton said:
I must be really getting slow in my old age. I've been trying to locate a
method either in Access, or if necessary in VBasic, to simply set the
default value of a textbox to the record number of the current record. In
other words, when presenting a user with an entry form for a new record, I'd
like to default a textbox to the record number of the record that will be
created.
And what determines the record number? Do you mean the record count (the
25th record get number 25)?
If so, will only one person be using the database to add records? If more
than one then using the DefaultValue property to do this will cause lots of
problems because multiple users can move to the new record position at the
same time. In fact one user could move to the new record position, the
default value would be displayed and that user could let the form sit like
that indefinitely before they actually fill out the form and save the
record. Any other user that adds a record during that time will get the
same value as the first user and whoever saves last will get an error
(assuming you are not allowing duplicates).
In addition, the DefaultValue property doesn't work for this in a
continuous or datasheet form even if there is only one user. If you open
the form and it has 24 records currently moving to where the new record
position is will show that it will attempt to use number 25 for the next
new record. As soon as you begin typing in the new record position another
new record position will be displayed to take its place. Since you haven't
saved the record yet the new record position will again use the number 25
since there are only 24 records actually saved in the table.
What you can do is use the BeforeUpdate event of the form to calculate the
next value and apply it to the record. Since BeforeUpdate fires a split
second before the record is saved there is very little chance for two
people to grab the same value. The only caveat is that this event can fire
multiple times for a given record over its lifetime so you need an If-Then
block to insure the number is only assigned to records that don't already
have a value.
If IsNull(Me![RecNum]) = True Then
Me![RecNum] = Nz(DMax("RecNum", "YourTableName"), 0)+1
End If
DCount() could be used if records were NEVER deleted, but DMax() is safer
since it doesn't matter if the number sequence currently has gaps in it.