Home > database >  Killing a VBA Script when the password is correct
Killing a VBA Script when the password is correct

Time:12-02

I'm a beginner in vba and i'm trying to block all cells except exception in a worksheet with an admin password. It's working but my problem is that i want to stop the script when the user write his password, he can have an acces to the worksheet until closing the worksheet.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim Pass As String 
Pass = "Test"

If Intersect(Target, Range("b6:b82, f6:f82, j6:j82, n6:n82, r6:r82")) Is Nothing Then 
    MsgBox "Vous devez disposer d'un accès administrateur pour modifier cette cellule." 
    frmLogin.Show 
    passform = frmLogin.txtPassword.Value 
    If passform <> Pass Then 
        MsgBox "Mot de passe érroné", vbExclamation, "Error" 
        Range("b6").Select 
    End If
End If


End Sub

I tried the Application.Wait and putting a End doesn't worked too. `

Thanks in advance

CodePudding user response:

If I understand you correct, you don't want to "kill the script"

  • you don't want to run it when you select another cell within the procedure because the user put in a wrong password
  • you don't want to run it, if the user has authenticated as admin

Regarding the first point: set Application.EnableEvents to false

Regarding the second point: Use a flag, e.g. m_isAdmin on module-level

Option Explicit

Private Const Pass As String = "Test"
Private m_isAdmin As Boolean

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If m_isAdmin = True Then Exit Sub 'no check necessary

Dim passform As String

If Intersect(Target, Range("b6:b82, f6:f82, j6:j82, n6:n82, r6:r82")) Is Nothing Then
    MsgBox "Vous devez disposer d'un accès administrateur pour modifier cette cellule."
    frmLogin.Show
    passform = frmLogin.txtPassword.Value
    If passform <> Pass Then
        MsgBox "Mot de passe érroné", vbExclamation, "Error"
        Application.EnableEvents = False
        Range("A1").Select
        Application.EnableEvents = True
    Else
        'if password is ok, set the module-level varialbe to true
        m_isAdmin = True
    End If
End If

End Sub
  • Related