VBA Code to Generate a Random Password with Specific Criteria in Excel

VBA Code:

' VBA Code to Generate a Random Password with Specific Criteria in Excel

Sub GenerateRandomPassword()
    Dim ws As Worksheet
    Dim rng As Range
    Dim passwordLength As Integer
    Dim password As String
    
    ' Set the worksheet and range to generate the password
    Set ws = ThisWorkbook.Worksheets("Sheet1") ' Replace with the name of your worksheet
    Set rng = ws.Range("A1") ' Replace with the cell where you want to generate the password
    
    ' Set the desired password length
    passwordLength = 8 ' Adjust as needed
    
    ' Generate the password with the specified criteria
    password = GenerateRandomPassword(passwordLength)
    
    ' Assign the generated password to the cell
    rng.Value = password
    
    ' Display a message
    MsgBox "Random password has been generated."
End Sub

Function GenerateRandomPassword(length As Integer) As String
    Dim validChars As String
    Dim password As String
    Dim i As Integer
    Dim charIndex As Integer
    
    ' Define the valid characters for the password
    validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-="
    
    Randomize ' Initialize the random number generator
    
    ' Generate the password by randomly selecting characters from the valid characters set
    For i = 1 To length
        charIndex = Int((Len(validChars) * Rnd) + 1)
        password = password & Mid(validChars, charIndex, 1)
    Next i
    
    GenerateRandomPassword = password
End Function


Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment