I write some data to an Access database, after which I retrieve the Autonumber that Access generates. Prior to writing the data, it sits in a class and all of the classes sit in a collection. The collection needs a unique string for each entry, so I create one until I can the proper one from Access. Just a place holder that’s unique. Specifically, I use this code:
If clsRoyaltyLine.RoyaltyLineID = 0 Then
clsRoyaltyLine.RoyaltyLineID = Int(Rnd * 100000)
mcolRoyLines.Add clsRoyaltyLine, CStr(clsRoyaltyLine.RoyaltyLineID)
If Not mobjParent Is Nothing Then
Set clsRoyaltyLine.Parent = Me.Parent
If this record has already been written to Access or has already been created, it will have a RoyaltyLineID that’s not zero. Otherwise I create a random number between 1 and 99,999 to serve as a unique id for the collection until such time as I can get a proper Autonumber from Access.
After thousands of RoyaltyLines processed, it finally broke. I was entering a particularly large order (the specific invoice line had 66 royalty lines), but only got to line 14 and I got a duplicate. The tenth RoyaltyLineID was the same as the fourteenth. To quote Phillip J. Fry:
Oh, the fools! If only they’d built it with 6,001 hulls! When will they learn?
I guess I’ll increase it by an order of magnitude, but is there a better way?