[英]User login form for excel vba
我正在尝试创建一个登录表单,其中用户名和密码输入与工作表上的数据匹配。 我尝试编码用户名或密码是否错误,它将显示一个msgbox并清除输入以重做。 但是当我测试该功能时,什么也没发生。 图片在这里
在这里编码
Private Sub login_Click()
Dim x, a As Double
a = WorksheetFunction.CountA(Range("A:A"))
If untb.Value = "" Then
MsgBox ("Enter the username"), vbOKOnly
ElseIf passtb.Value = "" Then
MsgBox ("Enter the password"), vbOKOnly
ElseIf untb.Value <> "" And passtb.Value <> "" Then
For x = 1 To a
If untb.Value = Cells(x, 2) And passtb.Value = Cells(x, 3) Then
Unload Me
MsgBox ("Welcome to Great Wines :)"), vbOKOnly
order.show
End If
Next x
Else
MsgBox ("Invalid username or password!"), vbOKOnly
untb.Value = ""
passtb.Value = ""
untb.SetFocus
End If
End Sub
您可以尝试这样的事情...
Private Sub login_Click()
Dim UserName As String, PW As String
Dim rngUser As Range
Dim firstUser As String
Dim UserFound As Boolean
If untb.Value = "" Then
MsgBox ("Enter the username"), vbOKOnly
untb.SetFocus
Exit Sub
End If
If passtb.Value = "" Then
MsgBox ("Enter the password"), vbOKOnly
passtb.SetFocus
Exit Sub
End If
UserName = untb.Value
PW = passtb.Value
With Range("B:B")
Set rngUser = .Find(UserName, lookat:=xlWhole)
If Not rngUser Is Nothing Then
firstUser = rngUser.Address
Do
If PW = rngUser.Offset(0, 1).Value & "" Then
UserFound = True
Unload Me
MsgBox ("Welcome to Great Wines :)"), vbOKOnly
Order.Show
Else
Set rngUser = .FindNext(rngUser)
End If
Loop While Not rngUser Is Nothing And firstUser <> rngUser.Address
Else
MsgBox "UserName is Incorrect!", vbExclamation, "UserName Not Found!"
untb.Value = ""
passtb.Value = ""
Exit Sub
End If
End With
If Not UserFound Then
MsgBox "Invalid password!", vbOKOnly
untb.Value = ""
passtb.Value = ""
untb.SetFocus
End If
End Sub
这应该可以处理您要尝试执行的操作。 您将需要With
表名称更新With
块,否则可能会遇到其他问题
Private Sub login_Click()
Dim LoginUser As Range
Dim FirstLoginUserAddress As String
Dim SuccessfulLogin As Boolean
If untb.Value <> "" And passtb.Value <> "" Then
' Update with the sheet reference where your login/passwords are kept. Otherwise, You will get issues
With Sheet1.Range("B:B")
Set LoginUser = .Find(untb.Value)
SuccessfulLogin = False
If Not LoginUser Is Nothing Then
FirstLoginUserAddress = LoginUser.Address
Do
If CStr(LoginUser.Offset(0, 1).Value2) = passtb.Value Then
SuccessfulLogin = True
Exit Do
Else
Set LoginUser = .FindNext(LoginUser)
End If
Loop Until LoginUser Is Nothing Or LoginUser.Address = FirstLoginUserAddress
End If
End With
If SuccessfulLogin = True Then
Unload Me
MsgBox ("Welcome to Great Wines :)"), vbOKOnly
Order.Show
Else
MsgBox ("Invalid username or password!"), vbOKOnly
untb.Value = ""
passtb.Value = ""
untb.SetFocus
End If
Else
MsgBox "Enter the " & IIf(untb.Value = vbNullString, "username", "password"), vbOKOnly
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.