One way to avoid conflicts in a multi-user environment is to store the last
number in a separate database which is opened exclusively to get the next
number. The following module does this:
''module begins'
Option Compare Database
Option Explicit
Dim dbsCounter As DAO.Database, rstCounter As DAO.Recordset
Public Function GetNextNumber() As Long
Const NOCURRENTRECORD As Integer = 3021
Set rstCounter = dbsCounter.OpenRecordset("tblCounter")
On Error Resume Next
With rstCounter
.Edit
' insert new row if table is empty
If Err = NOCURRENTRECORD Then
.AddNew
!NextNumber = 1
.Update
GetNextNumber = 1
Else
' update row and get next number in sequence
!NextNumber = !NextNumber + 1
.Update
GetNextNumber = rstCounter!NextNumber
End If
End With
End Function
Public Function OpenCounterDb(strCounterDb) As Boolean
' Opens external Counter database exclusively
' Returns True if able to open external database
Dim n As Integer, I As Integer, intInterval As Integer
' make 10 attempts to open external database exclusively
DoCmd.Hourglass True
SysCmd acSysCmdSetStatus, "Attempting to get new number"
On Error Resume Next
For n = 1 To 10
Err.Clear
Set dbsCounter = OpenDatabase(strCounterDb, True)
If Err = 0 Then
Exit For
Else
intInterval = Int(Rnd(Time()) * 100)
For I = 1 To intInterval
DoEvents
Next I
End If
Next n
SysCmd acSysCmdClearStatus
DoCmd.Hourglass False
If Err = 0 Then
OpenCounterDb = True
End If
End Function
Public Function CloseCounterDb()
On Error Resume Next
' close recordset and external databse if open
rstCounter.Close
dbsCounter.Close
Set rstCounter = Nothing
Set dbsCounter = Nothing
End Function
'module ends'
The external database is Counter.mdb with a table tblCounter with a Long
Integer column NextNumber.
The code is called like so, in this example in the context of a form bound
to the table containing the RIID column:
Dim strCounterDb As String, lngID As Long
strCounterDb = "F:\SomeFolder\Counter.mdb"
'attempt to get next number
If Not OpenCounterDb(strCounterDb) Then
MsgBox "Unable to get ID number at present.", vbInformation, "Error"
Else
Me!RIID = GetNextNumber()
' close external counter database
CloseCounterDb
End If