Hello everyone .
I wonna make a Password Generator, something like a 15 digits password . I know that I must use a "For i = 1 to 15" to repeat the code, but I'd like to know how I can randomize both numbers and letters.
Thanks in advance .
Printable View
Hello everyone .
I wonna make a Password Generator, something like a 15 digits password . I know that I must use a "For i = 1 to 15" to repeat the code, but I'd like to know how I can randomize both numbers and letters.
Thanks in advance .
In the Form's Load event call:Code:Dim I As Long
Dim strPassword As String
Dim intChar As Integer
For I = 1 to 15
Do
intChar = Int(Rnd * 75 + 48)
Loop Until (intChar >= Asc("0") And intChar <= Asc("9")) Or (intChar >= Asc("A") And intChar <= Asc("Z")) Or (intChar >= Asc("a") And intChar <= Asc("z"))
strPassword = strPassword & Chr(intChar)
Next I
Debug.Print strPassword
Randomize
Build a form with a label and a command button. Then apply this code:
This code produces 15-character random passwords containing numbers and both upper- and lower-case letters positioned randomly within the password. I assume that is what you wanted.Code:Private Sub Command1_Click()
Dim PassWord As String, RanNum As Integer, RanChar As String
For I = 1 To 15
Do
RanNum = Int(76 * Rnd + 47)
Select Case RanNum
Case 48 To 57, 65 To 90, 97 To 122
Exit Do
Case Else
End Select
Loop
PassWord = PassWord & Chr$(RanNum)
Next
Label1.Caption = PassWord
End Sub
Private Sub Form_Load()
Randomize
Label1.Caption = vbNullString
End Sub
Really Helpfull guys.
Thanks =)
A bit late, but for possibly interested here is a non-specialized, generic function that can be built on the idea:
To get the same results as above you'd call this like:Code:Public Function StrRnd(ByVal Length As Long, Optional Chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") As String
Dim I As Long
StrRnd = Space$(Length)
For I = 1 To Length
Mid$(StrRnd, I, 1) = Mid$(Chars, Int(Rnd * Len(Chars)) + 1)
Next I
End Function
MsgBox StrRnd(15, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
Nice idea, Merri. Build the string first and select the Mid$() randomly. That eliminates the Do...While loop and rejected random numbers. The big string can be produced at Form Load and stored Public. Here's a revision to my code based on what I learned by studying yours:
Note, rather than typing an enormous string take a look at my Form Load.Code:Dim BigStr As String
Private Sub Command1_Click()
Dim PassWord As String
PassWord = Space$(15)
For I = 1 To 15
Mid$(PassWord, I, 1) = Mid$(BigStr, Int(Rnd * Len(BigStr) + 1), 1)
Next
Label1.Caption = PassWord
End Sub
Private Sub Form_Load()
Randomize
Label1.Caption = vbNullString
For I = 48 To 122
Select Case I
Case 48 To 57, 65 To 90, 97 To 122
BigStr = BigStr & Chr$(I)
Case Else
End Select
Next
End Sub