2014-02-22 65 views
0

我有一些麻煩我的代碼爲用戶窗體命令按鈕單擊事件處理程序用戶窗體登錄嘗試計數器,3次嘗試

工作當用戶輸入了不正確的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

聲明一個過程之外的變量與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 
+0

完美。我非常感謝你,謝謝! – Roberto1991