我有一组密码,如果它包含1个数字,1个大写,1个小写,如果长度为8个字符,我需要验证每个密码。
我制作了这段代码,但它不适用于角色,只是长度。 你能帮我吗?谢谢!
Sub Password()
Dim b As Integer
Dim i As Integer, j As Integer, k As Integer
Dim psw As String
Dim LengthOFPasswordsList As Long
LengthOFPasswordsList = Range("D" & Rows.Count).End(xlUp).Row
For b = 3 To LengthOFPasswordsList
psw = Range("D" & b)
If i >= 65 Or i <= 90 Then
If j >= 97 Or j <= 122 Then
If k > 48 Or k <= 57 Then
If psw <> (Chr(i) & Chr(j) & Chr(k) & Chr(i Or j Or k) _
& Chr(i Or j Or k) & Chr(i Or j Or k) & Chr(i Or j Or k)) _
And Len(psw) <> 8 Then
Range("F" & b) = "Password Inválida"
End If
End If
End If
End If
Next b
End Sub
答案 0 :(得分:2)
这样的事情如何并使用内置功能:
Sub PasswordCheck ()
Dim bNum as Boolean, bUpper as Boolean, bLower as Boolean
Dim lRow as Long, x as Long
Dim i as Integer
Dim sPWD as String
lRow = Range("D" & Rows.Count).End(xlUp).Row
For x = 1 to lRow 'Go through each Password
bNum = False
bUpper = False
bLower = False
sPWD = Range("D" & x)
For i = 1 to Len(sPWD) 'Go through each letter
If IsNumeric(Mid(sPWD, i, 1) Then
bNum = True
ElseIf Mid(sPWD, i, 1) Like "[A-Z]" Then
bUpper = True
ElseIf Mid(sPWD, i, 1) Like "[a-z]" Then
bLower = True
End If
Next i
If bNum And bUpper And bLower Then
'Password is valid
Else
'Password is Invalid
Range("F" & x) = "Password Inválida"
End If
Next x
End Sub
答案 1 :(得分:1)
看起来你想要立刻做太多事情。分解代码没有什么特别的错误。很多时候,它更容易阅读和理解正在发生的事情。
Sub Password()
Dim b As Integer
Dim i As Integer, j As Integer, k As Integer
Dim psw As String
Dim hasNum As Boolean, hasUpper As Boolean, hasLower As Boolean
Dim LengthOFPasswordsList As Long
LengthOFPasswordsList = Range("D" & Rows.Count).End(xlUp).Row
For b = 3 To LengthOFPasswordsList
'assume the password is no good.
hasNum = False
hasUpper = False
hasLower = False
'capture the psw in question
psw = Range("D" & b)
'see if there is a number in the password
'NOTE: the following For loops uses the ASCII values for numbers and letters.
For k = 48 To 57
If (InStr(1, psw, Chr(k))) Then
hasNum = True
Exit For
End If
Next k
'See if there is an upper case
For i = 65 To 90
If (InStr(1, psw, Chr(i))) Then
hasUpper = True
Exit For
End If
Next i
'See if there is a lower case
For j = 97 To 122
If (InStr(1, psw, Chr(j))) Then
hasLower = True
Exit For
End If
Next j
'See if all criteria was met
If Not hasLower Or Not hasUpper Or Not hasNum Or (Len(psw) <> 8) Then
Range("F" & b) = "Password Inválida"
End If
Next b
End Sub
答案 2 :(得分:1)
我个人会使用正则表达式。只需检查您的每个条件,如果其中任何一个不匹配,则密码失败。验证函数可以这么简单:
'Requires a reference to Microsoft VBScript Regular Expressions x.x
Private Function ValidPassword(inValue As String) As Boolean
Dim criteria As Variant
With New RegExp
For Each criteria In Split(".{8},[A-Z],[a-z],[0-9]", ",")
.Pattern = criteria
If Not .Test(inValue) Then Exit Function
Next
End With
ValidPassword = True
End Function
这也极大地简化了调用代码:
Sub Password()
Dim b As Integer
For b = 3 To Range("D" & Rows.Count).End(xlUp).Row
If Not ValidPassword(Range("D" & b)) Then
Range("F" & b) = "Password Inválida"
End If
Next
End Sub