Userform登录尝试计数器,3次尝试后关闭

时间:2014-02-22 19:52:52

标签: vba variables excel-vba userform excel

我在使用userform命令按钮单击事件处理程序

时遇到问题

当用户输入错误的ID和密码时,消息框会通知他们剩余的尝试次数。我在设置我的计数器变量时遇到问题。如果我在事件处理程序中设置计数器值,它将永远不会改变。所以我试图从另一个来源传递计数器。我也不能使用公共变量。这是我的验证码。

Private Sub CommandButton1_Click()

    Dim Userid As String, password As String, SearchID As String
    Dim myfind As Range, col As Integer, count As Integer

    Userid = Useridtextbox
    password = Passwordtextbox
    SearchID = Userid & " " & password
    col = 1

    Set myfind = Sheets("User Master File Records").Range("A:A").Find(What:=SearchID,
    After:=Cells(col, 1), LookIn:=xlValues, lookat:= _
    xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)

    If Userid = "" Then
        Label3.Caption = "Enter User ID"
    ElseIf password = "" Then
        Label4.Caption = "Enter Password"
    ElseIf myfind Is Nothing Then
        MsgBox "Access denied, You have " & count & " attempts left until the system closes"

    Else: MsgBox "access granted"

    End If

    count = count - 1
    If count = 0 Then MsgBox "bye"

End Sub

我无法理解如何做到这一点,并且我已尽力搜索我所知道的每个论坛。我认为这很简单,但我是VBA的新手。任何人都可以给我一些关于如何在另一个子中设置计数器值以及如何在此事件处理程序中使用它的输入吗?

谢谢大家

1 个答案:

答案 0 :(得分:1)

使用Private访问修饰符在过程外声明变量允许在整个模块/表单中使用它:

'// this variable is visible to all code in the UserForm:
Private mCounter As Long

'// keep the magic number easily modifiable
Private Const MAX_LOGIN_ATTEMPTS As Long = 3

Private Sub CommandButton1_Click()

    // your validation logic
    ok = false

    If Not ok Then '// test
        mCounter = mCounter + 1

        If mCounter < MAX_LOGIN_ATTEMPTS Then
            MsgBox "Access denied, You have " & (MAX_LOGIN_ATTEMPTS - mCounter) & " attempts left until the system closes"
        Else
            MsgBox "bye"
            '//...
        End If
    Else
        MsgBox "access granted"
        '//...
    End If
End Sub