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 techguruplus telegram group Join Our WhatsApp Group techguruplus whatsapp group
Nazim Khan - Author Image

Nazim Khan (Author) 📞 +91 9536250020
[MBA in Finance]

Nazim Khan is an expert in Microsoft Excel. He teaches people how to use it better. He has been doing this for more than ten years. He is running this website (TechGuruPlus.com) and a YouTube channel called "Business Excel" since 2016. He shares useful tips from his own experiences to help others improve their Excel skills and careers.

Leave a Comment