سؤال

I'm having some trouble getting my code to work for a userform command button click event handler

When a user inputs an incorrect ID and Password a messagebox informs them how many tries they have remaining. I'm having trouble setting my counter variable. If i set the counter value in the event handler it will never change. So i'm attempting to pass the counter from another source. I also can not use public variables. Here is the validation code i have.

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

I'm having trouble understanding how to do this and i've tried to my best ability to search every forum i know of. I assume this is pretty simple to do but i'm new to VBA. Could anyone give me some input on how to set the counters value in another sub and how to use it in this event handler?

Thanks everyone

هل كانت مفيدة؟

المحلول

Declaring a variable outside a procedure with the Private access modifier allows it to be used throughout the module/form:

'// 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top