I have created a basic login system that asks the user for a password. Here's a list of what it does:
- When you run the code it will open an Inputbox asking you for a password.
- There is one criteria: You have to enter a password of 8 characters. If you enter a password with less or more, it will give you an error message.
- If you leave the Inputbox blank or press Cancel, it will switch over to a Yes or No msgbox asking you if you want to quit the macro. Yes will close and No, will bring you back to the Inputbox.
I believe that there are many ways to optimize the code. Are there any suggestions?
Sub Userlogin(Password, ExitApplication)
Dim Confirm
Dim PasswordLength As Integer
' Password System
If Password = "" Then
' Loop until Password is correct.
Do While Password = ""
Password = InputBox("Enter your Password:", "Login")
PasswordLength = Len(Password)
' Asks the user if they want to close the application.
If Password = "" Then
Confirm = MsgBox("Are you sure you want to close this application?", vbYesNo, "Confirm")
End If
If Confirm = vbYes Then
ExitApplication = True
Exit Do
Exit Sub
End If
If Confirm = vbNo Then
Password = ""
PasswordLength = 8
Confirm = ""
End If
' Checks if the Password is 8 characters.
If Not PasswordLength = 8 Then
MsgBox "The Password must be 8 characters long." & vbNewLine & vbNewLine & "Please Try again.", vbCritical, "Password Incorrect"
Password = ""
End If
Loop
End If
End Sub
Main Sub is here:
Sub MainSub()
' Standard Dim's
Dim Username As String
Dim Password As String
Dim ExitApplication As Boolean
'_______________________________________________________________________________
' Set Values
ExitApplication = False
Username = CreateObject("WScript.Network").Username
'_______________________________________________________________________________
Call Userlogin(Password, ExitApplication)
If ExitApplication = True Then
Exit Sub
End If
End Sub
Sub
is being used? I.e. a couple lines of the calling code? \$\endgroup\$ – Comintern Dec 8 '16 at 14:20