In this article, you will learn how to create a login application in Excel using Visual Basic for Applications (VBA). With Excel VBA, you can automate tasks in Excel using macros. We'll create a simple macro that will be executed after clicking on a command button.
Below we are going to discuess step by step n example of how you can design the login interface using a UserForm in Excel VBA:
ba
Copy code
' Code for the UserForm named "LoginForm"
Private Sub UserForm_Initialize()
' Set the title of the UserForm
Me.Caption = "Login"
' Add a label for username
Dim lblUsername As MSForms.Label
Set lblUsername = Me.Controls.Add("Forms.Label.1", "lblUsername", True)
With lblUsername
.Caption = "Username:"
.Left = 10
.Top = 10
End With
' Add a TextBox for username input
Dim txtUsername As MSForms.TextBox
Set txtUsername = Me.Controls.Add("Forms.TextBox.1", "txtUsername", True)
With txtUsername
.Width = 150
.Left = 100
.Top = 10
End With
' Add a label for password
Dim lblPassword As MSForms.Label
Set lblPassword = Me.Controls.Add("Forms.Label.1", "lblPassword", True)
With lblPassword
.Caption = "Password:"
.Left = 10
.Top = 40
End With
' Add a TextBox for password input
Dim txtPassword As MSForms.TextBox
Set txtPassword = Me.Controls.Add("Forms.TextBox.1", "txtPassword", True)
With txtPassword
.Width = 150
.Left = 100
.Top = 40
.PasswordChar = "*" ' Mask the password characters
End With
' Add a CommandButton for login action
Dim btnLogin As MSForms.CommandButton
Set btnLogin = Me.Controls.Add("Forms.CommandButton.1", "btnLogin", True)
With btnLogin
.Caption = "Login"
.Width = 60
.Left = 100
.Top = 70
End With
End Sub
Private Sub CommandButton1_Click()
Dim username As String
Dim password As String
' Retrieve username and password from TextBoxes
username = TextBox1.Value
password = TextBox2.Value
' Check if username and password are correct
If ValidateUser(username, password) Then
' Provide access to the spreadsheet or perform desired actions
MsgBox "Login successful!", vbInformation
' Add code to open the main worksheet or perform other tasks
Else
MsgBox "Invalid username or password. Please try again.", vbExclamation
End If
End Sub
Function ValidateUser(username As String, password As String) As Boolean
Dim userDatabase As Worksheet
Dim lastRow As Long
Dim i As Long
' Assuming user database is stored in a worksheet named "Users"
Set userDatabase = ThisWorkbook.Sheets("Users")
' Find the last row in the user database
lastRow = userDatabase.Cells(userDatabase.Rows.Count, 1).End(xlUp).Row
' Loop through each row to check for matching username and password
For i = 2 To lastRow ' Assuming data starts from row 2, and column A contains usernames, column B contains passwords
If userDatabase.Cells(i, 1).Value = username And userDatabase.Cells(i, 2).Value = password Then
ValidateUser = True
Exit Function
End If
Next i
ValidateUser = False ' If no matching username and password found
End Function