Search code examples
vbams-accesscode-access-security

How to set a limit the number of times a message box in Access will display


I have added a login form to an Access Database. I am trying to figure out a way to limit the number of times a user can enter an incorrect password. In the VBA code shown below, when the user inputs a password that is incorrect, the following message box triggers, "MsgBox "Incorrect password", vbOKOnly + vbExclamation".

I would like the user to get three failed attempts before a different message box appears. Something like, "Please contact administrator"...

Thanks in advance for the help.

Private Sub OkBTN_Click()

        'Check that User is selected
    If IsNull(Me.cboUser) Then
        MsgBox "You forgot to select your name from the drop down menu!", vbCritical
        Me.cboUser.SetFocus
    Else
        
    'Check for correct password
    If Me.txtPassword = Me.cboUser.Column(2) Then
        
    'Check if password needs to be reset
    If Me.cboUser.Column(4) Then
        DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
    End If

        Me.Visible = False
        Else
        MsgBox "Incorrect password", vbOKOnly + vbExclamation
        
        Me.txtPassword = Null
        Me.txtPassword.SetFocus
        End If
    End If

End Sub

Solution

  • In this situation I think I'd declare a Static counter variable. The value of a static variable is preserved between procedure calls. Other alternatives would be to store the count in a a global variable, use a TempVar, or write them to a table.

    Private Sub OkBTN_Click()
    
        Static intIncorrectCount As Integer ' The value of a static variable is preserved between procedure calls.
    
        'Check that User is selected
        If IsNull(Me.cboUser) Then
            MsgBox "You forgot to select your name from the drop down menu!", vbCritical
            Me.cboUser.SetFocus
        Else
    
            'Check for correct password
            If Me.txtPassword = Me.cboUser.Column(2) Then
    
                'Check if password needs to be reset
                If Me.cboUser.Column(4) Then
                    DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
                End If
                Me.Visible = False
                intIncorrectCount = 0
                
            ElseIf intIncorrectCount > 2 Then
                MsgBox "Too many incorrect attempts.  Closing Access.", vbOKOnly + vbExclamation
                'DoCmd.Quit ' ### Save your code before enabling this line.  ###
                
            Else
                MsgBox "Incorrect password", vbOKOnly + vbExclamation
    
                Me.txtPassword = Null
                Me.txtPassword.SetFocus
                intIncorrectCount = intIncorrectCount + 1
            End If
        End If
    
    End Sub