Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
Option Explicit
Public Enum enumNewIDType
NewIDMaximum = 1
FindFirstFreeID = 2
End Enum
Public Function GetNewID(strTableName As String, strPK_FieldName As String, NewIDMode As enumNewIDType) As Long
On Error GoTo Err_Trap
Dim rs As Object
Dim s As String
Dim k As Integer
Dim blnFound As Boolean
Select Case NewIDMode
Case 1 'NewIDMaximum
s = "SELECT Max(" & strPK_FieldName & ") FROM " & strTableName
Set rs = CurrentDb.OpenRecordset(s)
GetNewID = Nz(rs.Fields(0), 0) + 1
Case 2
s = "SELECT " & strPK_FieldName & " FROM " & strTableName & " ORDER BY " & strPK_FieldName
Set rs = CurrentDb.OpenRecordset(s)
If rs.RecordCount = 0 Then
GetNewID = 1
blnFound = True
Else
Dim prevID As Long
Dim currID As Long
prevID = rs.Fields(0)
rs.MoveNext
Do While Not rs.EOF
currID = rs.Fields(0)
If (currID - prevID) > 1 Then
If IsUniqueID(strTableName, strPK_FieldName, prevID + 1) = True Then
GetNewID = prevID + 1
blnFound = True
Exit Do 'For
End If
Else
prevID = rs.Fields(0)
rs.MoveNext
End If
Loop
End If
If blnFound = False Then
GetNewID = prevID + 1 'rs.Fields(0) + 1
End If
End Select
Exit_Here:
Exit Function
Err_Trap:
Select Case Err.Number
Case Is <> 0
MsgBox Err.Number & " - " & Err.Description
Stop
Resume Exit_Here
End Select
End Function
Public Function IsUniqueID(strTableName As String, strIDFieldName As String, strIDValue As String) As Boolean
Dim rs As Object
Dim s As String
Set rs = CurrentDb.OpenRecordset("SELECT * FROM " & strTableName)
s = strTableName & "." & strIDFieldName & " = " & strIDValue
rs.FindFirst s
If rs.NoMatch Then
IsUniqueID = True
Else
IsUniqueID = False
End If
Set rs = Nothing
End Function
Dim lngNewID as Long
lngNewID = GetNewID("YourTableName", "PrimKeyFieldName",NewIDMaximum )
'then do whatever you want with this new ID; or you can
'declare another argument to the GetNewID function, which
'passes the value of that number you mentioned in your post