MACRO LIBRARY

Lesson 1.6 homework part A solution

Free public access. No account or subscription required.

Files

Lesson 1.6 homework part A solution

Code

'Homework 1.6a
'Create a macro that prompts the user to enter a password ("solidworksrules") with an input box. _
    They have three tries to enter the correct password, otherwise the macro ends.  Each time an _
    incorrect password is entered, the user is prompted to retry or cancel, and is informed of _
    how many tries he has left.  If the correct password is entered, a message box is displayed _
    stating that the correct password was entered.
    
Option Explicit
    
Dim strPassword As String
Dim blnSuccess As Boolean
Dim intTries As Integer
Dim retval As String
    
Sub main()
    'initialize variables
    intTries = 3
    blnSuccess = False
    
    'user must 'succeed' in entering the correct password, upon which blnSucess becomes _
        true and the rest of the macro runs
    While blnSuccess = False
        'ask user to enter password
        strPassword = InputBox("Please enter the password." & vbCrLf & _
        "You have " & intTries & " tries remaining.")
        'if the user pressed cancel then a 0 length string is returned, and the macro ends
        If strPassword = "" Then End
        'check to see if password is correct
        If strPassword <> "solidworksrules" Then
            'if not, then reduce the "tries" user has available and prompt user to try _
                again, if he/she desires, unless the "tries" are exhausted, in which _
                case the macro ends
            intTries = intTries - 1
            If intTries = 0 Then
                MsgBox "Sorry, you have no more tries remaining. Macro will end."
                End
            End If
            retval = MsgBox("Sorry, incorrect password." & vbCrLf & _
                "Would you like to re-enter the password?", vbYesNo)
            'if the user does not want to try again, end the macro
            If retval <> vbYes Then End
        Else
            blnSuccess = True
        End If
    Wend
    MsgBox "You entered the correct password!"
End Sub