How do I generate a random string of characters to create a Captcha? (1 Viewer)

Cark

Registered User.
Local time
Today, 06:18
Joined
Dec 13, 2016
Messages
153
I have an Access database where I would like to create a Captcha on a Form. I'm doing it more as a test of my VBA knowledge, but I have hit a snag where I have been unable to get my code to completely randomise the string generated.

The string (displayed below the Captcha label) is what I will refer to as the Captcha string. The Captcha string is generated during the Form's On Load event using the following code:

Code:
Private Sub Form_Load()
    
    Dim CaptchaString As String * 8
    Dim n As Integer
    Dim ch As Integer
    For n = 1 To Len(CaptchaString)
        Do
            ch = Rnd() * 127

        Loop While ch < 48 Or ch > 57 And ch < 65 Or ch > 90 And ch < 97 Or ch > 122
        Mid(CaptchaString, n, 1) = Chr(ch)
    Next

    Debug.Print CaptchaString
    Me.CaptchaBox.Caption = CaptchaString
    
    
    CaptchaString = ""

End Sub

When I open my database for the first time it loads with the Captcha string showing ZDJbagZ5 every single time.

When I close the Form (but keep the database open) and then reopen it, it shows ndzoyCaK every single time.

It seems as though it is not generating randomly like I thought the code would.

Any idea on how to fix this? I want a completely unique code each time I open the Form.
 

Attachments

  • CaptchaFormResizing.accdb
    576 KB · Views: 102

vba_php

Forum Troll
Local time
Today, 08:18
Joined
Oct 6, 2019
Messages
2,880
Cark,

I did not look at your file and it's been a while for me regarding this concept, but I looked it up as a reminder to myself:

https://www.google.com/search?q=ms+access+vba+randomize+reset+seed+value

and I think what they're talking about here is also relevant to your issue:

https://stackoverflow.com/questions/2884972/repeating-random-variables-in-vba

and if you're not afraid of downloading archive directories, there is an example of the same type of randomizing you're trying to do in the package I presented to this gentleman: https://www.access-programmers.co.uk/forums/showpost.php?p=1659079&postcount=10
 

isladogs

MVP / VIP
Local time
Today, 14:18
Joined
Jan 14, 2017
Messages
18,209
I've also not looked at your file or the links in the last reply

Try adding the line Randomize …
Surprised that first line works

Code:
  Dim CaptchaString As String * 8

    Dim n As Integer
    Dim ch As Integer
    Randomize
    For n = 1 To Len(CaptchaString)
    'rest of code
 

Cark

Registered User.
Local time
Today, 06:18
Joined
Dec 13, 2016
Messages
153
Yep, the Randomize function did the trick.
 

isladogs

MVP / VIP
Local time
Today, 14:18
Joined
Jan 14, 2017
Messages
18,209
Hi Cark
Glad its now working for you. Good luck
 

Users who are viewing this thread

Top Bottom