Sample output :
"ADF3V3224K1WQ"
(12 characters long , Higher caps Alphabetical letters , and Numeric values aswell).
Story
I'm having a hard time figuring out how to create a string generator (didn't say it has to be random, but it 100% has to be unique, meaning it has to check for duplications or store existing values), I have no experience with VBA. I already found a similar post here, but it is different then mine, as it does not specifically ask for the string to be 100% unique. (I don't need a very low chance, I need 100% across the board).
Syntax-wise I'm pretty confused, I managed to find where the code behind events are, ie Button presses, so I know where I need to write it, but I have no idea how to check for duplications. (even relying on a time seed that can ensure it will be 100% unique is great).
Link to the similar post: MS Access Visual Basic - generate random string in text field
Well, I guess if it really needs to be alphanumeric and unique, this is the way to go:
This code generates a random string of characters based on the current time (like the answer by @paul-bica), only it encodes them alphanumerically and uses the timer to get fractions of a second to reach 12 characters). This way you should be able to generate multiple random strings per second.
Just call UniqueTimeBasedString()
to get the string.
(Note that if you use this function in a query, Access will cache the result and it won't be unique at all).
Public Function UniqueTimeBasedString() As String
Dim alphanumericCharacters As String
alphanumericCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim timeString As String
timeString = Format(Now, "yymmddhhmmss") & Getmtimestring(6)
Dim c As Integer
Dim intTimepart As Integer
c = 1
Do While c < Len(timeString)
intTimepart = CInt(Mid(timeString, c, 3))
c = c + 3
UniqueTimeBasedString = UniqueTimeBasedString & Mid(alphanumericCharacters, Int(intTimepart / 61) + 1, 1) & Mid(alphanumericCharacters, intTimepart Mod 61 + 1, 1)
Loop
End Function
Public Function Getmtimestring(length As Integer) As String
Dim mtime As Double
mtime = Timer()
Dim mtimeLng As Long
mtimeLng = Int((mtime - Int(mtime)) * (10 ^ length))
Getmtimestring = CStr(mtimeLng)
Do While Len(Getmtimestring) < length
Getmtimestring = "0" & Getmtimestring
Loop
End Function
Notes:
Timer()
isn't really accurate, and this can theoretically cause
problemsGetmtimestring
will just return zeroes)