Excel生成随机密码

针对生成一个8到12位包含大小写字母、数字、以及特殊字符的随机密码的需求,我们可以采用VBA来实现,以确保每种字符至少包含一次,同时随机生成密码长度。下面是一个更贴近需求的VBA函数示例:

Function GenerateComplexPassword() As String
    Dim passwordLength As Integer
    Dim lowercase As String
    Dim uppercase As String
    Dim numbers As String
    Dim specialChars As String
    Dim allChars As String
    Dim password As String
    Dim i As Integer

    ' 初始化字符集
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numbers = "0123456789"
    specialChars = "!@#$%^&*"
    allChars = lowercase & uppercase & numbers & specialChars

    ' 随机密码长度8到12位
    passwordLength = Int((12 - 8 + 1) * Rnd + 8)

    ' 确保密码包含至少一个小写字母、一个大写字母、一个数字和一个特殊字符
    password = Mid(lowercase, Int((Len(lowercase) * Rnd) + 1), 1) & _
               Mid(uppercase, Int((Len(uppercase) * Rnd) + 1), 1) & _
               Mid(numbers, Int((Len(numbers) * Rnd) + 1), 1) & _
               Mid(specialChars, Int((Len(specialChars) * Rnd) + 1), 1)

    ' 填充剩余长度
    For i = 5 To passwordLength
        password = password & Mid(allChars, Int((Len(allChars) * Rnd) + 1), 1)
    Next i

    ' 打乱密码以增加随机性
    GenerateComplexPassword = ShuffleString(password)
End Function

' 一个简单的字符串打乱函数
Function ShuffleString(s As String) As String
    Dim arr() As String
    Dim i As Long
    Dim j As Long
    Dim temp As String

    ReDim arr(1 To Len(s))
    For i = 1 To Len(s)
        arr(i) = Mid(s, i, 1)
    Next i

    ' 打乱数组
    For i = 1 To Len(s)
        j = Int((Len(s) - i + 1) * Rnd + i)
        temp = arr(i)
        arr(i) = arr(j)
        arr(j) = temp
    Next i

    ' 重组为字符串
    ShuffleString = Join(arr, "")
End Function

VBA脚本首先定义了一个GenerateComplexPassword函数,用于生成随机密码。它确保了密码至少包含一个小写字母、一个大写字母、一个数字和一个特殊字符。然后,它填充剩余的字符以达到随机选择的长度(8到12位之间)。最后,使用ShuffleString函数打乱密码中的字符,以提高密码的随机性和安全性。

Alt + F11打开Excel的VBA编辑器,插入一个模块,并将上面的代码粘贴进去。保存后,你可以在Excel公式中通过调用=GenerateComplexPassword()来生成一个随机的、复杂的密码。

posted @ 2024-03-28 14:07  自律™  阅读(158)  评论(0编辑  收藏  举报