Monday, May 26, 2008

Prompting for a password before running a VBA code

The macro below will help you set a custom password for running a macro in workbook. Let’s say you have a run query button on your worksheet and you want to make sure before running the codes behind this query user needs to be authenticated.


Private Sub CommandButton1_Click()

Dim strPass As String ' This sting is password

Dim lCount As Long

For lCount = 1 To 3

strPass = InputBox(Prompt:="Password Please", Title:="PASSWORD REQUIRED")

If strPass = vbNullString Then 'Cancelled

sLast.Select

Exit Sub

ElseIf strPass <> "Password" Then 'InCorrect password

MsgBox "Password incorrect", vbCritical, "Failed"

Else 'Correct Password

Exit For

End If


Next lCount

If lCount = 4 Then 'They use up their 3 attempts

MsgBox "The password is wrong, workbook is going close", vbInformation

ActiveWorkbook.Close SaveChanges:=False

Exit Sub

Else

MsgBox "Correct Password", vbOKOnly 'put your codes from hear on

End If

End Sub

No comments:

Post a Comment