Solved

Identify the maximum number in a field before a gap in an sequence on before insert event using vba

Posted on 2016-10-21
8
61 Views
Last Modified: 2016-10-23
I tried all day searching forums to find an answer but  I couldn't find any.. I hope someone could help me here.
the "BookID" is a field in the table for auto generated ID number for the book  This is what I' m using at the moment

Private Sub Form_BeforeInsert(Cancel As Integer)
TxBook = Nz(DMax("BookID", "Tbl_Books"), 0) + 1  'and works fine
end sub


Works fine but what I need is  if one book or more is deleted I want it to inset the lowest missing number then if nothing misiing will inset the maximum number
0
Comment
Question by:Ronald Malk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 51

Expert Comment

by:Ryan Chong
ID: 41853529
>>Works fine but what I need is  if one book or more is deleted I want it to inset the lowest missing number then if nothing misiing will inset the maximum number

so you mean to reuse the so called "deleted id" for your new entry? from my opinion, you should use the new id instead of re-using the "deleted id" to maintain your data integrity.
1
 
LVL 50

Expert Comment

by:Gustav Brock
ID: 41853534
Yes, seems like a very bad idea.

Leave the old Id, but mark it as Deleted or Obsolete (a boolean field).
Then proceed as you do now.

For a current list of books, filter on Obsolete = False

/gustav
1
 
LVL 57
ID: 41853548
An auto number for a primary key is a meaningless key and you're trying to apply meaning to it by having the sequence represent something. That's why you're not finding any solutions on this.

 There's no reason to do what you're trying to do,  and as Ryan pointed out good reasons for not doing it.

As Gustav  pointed out, there are other ways to handle situations that you might have. What is it that you're trying to achieve by reusing these old numbers?

Jim
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 50

Expert Comment

by:Gustav Brock
ID: 41853553
It should be noted that - if you insist - it can easily be done.
You can create a list of missing numbers:
Private Sub btnSearch_Click()

' Read table/query sequentially to 
' record all missing IDs.
' Fill a ListBox with missing values.
' A reference to Microsoft DAO must be 
' present.

  ' Define search table or query.
  Const cstrTable As String = "Orders"
  Const cstrField As String = "OrderID"
  
  Dim dbs As DAO.Database
  Dim rst As DAO.Recordset
  Dim lst As ListBox
  Dim col As Collection
  
  Dim strSQL As String
  Dim strList As String
  Dim lngLast As Long
  Dim lngNext As Long
  Dim lngMiss As Long
    
  strSQL = "Select " & cstrField & "" _
   & " From " & cstrTable & " _
   & " Order By 1;"  
  
  Set lst = Me!lstMissing
  Set col = New Collection
  Set dbs = CurrentDb
  Set rst = dbs.OpenRecordset(strSQL)
  
  If rst.RecordCount = 0 Then
    'The recordset is empty.
    'Nothing to do.
  Else
    lngLast = rst(cstrField).Value
    rst.MoveNext
    While rst.EOF = False
      lngNext = rst(cstrField).Value
      For lngMiss = lngLast + 1 To _
       lngNext - 1
        col.Add (lngMiss)
      Next
      lngLast = lngNext
      rst.MoveNext
    Wend
      'Generate next value in sequence.
      'Discard if collecting only 
      'missing values.
      col.Add (lngLast + 1)
  End If
  rst.Close
  
  'Populate list box from collection.
  For lngMiss = 1 To col.Count
    If Len(strList) > 0 Then 
      strList = strList & ";"
    End If
    strList = strList & col(lngMiss)
    Debug.Print col(lngMiss)
  Next
  lst.RowSource = strList
  Debug.Print strList
  
  Set rst = Nothing
  Set dbs = Nothing
  Set col = Nothing
  Set lst = Nothing
  
End Sub

Open in new window

The full story is here:

Find and Generate Missing Values in an Access Table

/gustav
0
 
LVL 30

Expert Comment

by:hnasr
ID: 41854725
For a table a(..., f3)
f3
1
2
4
5

This query gives the next lowest missing number:
SELECT Min(x.f3)+1 AS Expr1
FROM a AS x
WHERE (((Exists (Select f3 from a y WHERE y.f3=x.f3+1))=False));

Open in new window

Result 3
This a VBA code for a function to return the next value as a variable:

Private Function nextValue()
    Dim rs2 As Recordset
    Set rs2 = CurrentDb.OpenRecordset("SELECT Min(x.f3)+1 FROM a AS x WHERE (((Exists (Select f3 from a y WHERE y.f3=x.f3+1))=False))")
    nextValue = rs2(0)
End Function

'to use, you may set txtBox1 = nextValue()
Private Sub Command40_Click()
     Debug.Print nextValue()
End Sub

Open in new window

Result 3
0
 
LVL 30

Accepted Solution

by:
hnasr earned 500 total points
ID: 41854910
@Ronald Malk
Try this sample database. If still in doubt attach a representative copy of your database.
Check the code in the before insert event.
Private Function nextValue()
    'this code selects the minimum value of a filed in a table
    'where the next value is missing from the table
    'x and y are called aliases to allow using the same table in different nested queries
    'so the x.fld is compared to the y.fld
    Dim rs2 As Recordset
    Set rs2 = CurrentDb.OpenRecordset("SELECT Min(x.BookID)+1 FROM Tbl_Books AS x WHERE (((Exists (Select BookID from Tbl_Books y WHERE y.BookID=x.BookID+1))=False))")
    nextValue = rs2(0)
End Function
Private Sub Form_BeforeInsert(Cancel As Integer)
    BookID = nextValue()
End Sub

Open in new window

TblBooks.accdb
1
 

Author Comment

by:Ronald Malk
ID: 41855746
Thank you so much it works very good, It's something new for me, First time I do VBA this way, I still need to teach my self more of the internet that where I'm learning from.
0
 
LVL 30

Expert Comment

by:hnasr
ID: 41855777
Welcome!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In a multiple monitor setup, if you don't want to use AutoCenter to position your popup forms, you have a problem: where will they appear?  Sometimes you may have an additional problem: where the devil did they go?  If you last had a popup form open…
Access custom database properties are useful for storing miscellaneous bits of information in a format that persists through database closing and reopening.  This article shows how to create and use them.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question