Auto populate user id based on login info - ms-access

I am working on a sales CRM database in MS access 2010. I am trying to auto populate usernames in various forms.
The DB loads to a login page, asking for username and password. The username is set in the Employee table, not based on Windows login. The employee table has the following fields (EmpID PK, firstname, lastname, phone, email, notes, title, username TEXT, password).
I have two tables (Customer Contact and Leads) that require an employee to 'take ownership' of the activity. I would like the employee field to auto populate based on who is logged in.
Here is the code behind the OK button on my login page:
Private Sub Command1_Click()
If IsNull(Me.txtUserID) Then
MsgBox "Please enter user name.", vbInformation, "User Name Required"
ElseIf IsNull(Me.txtPassword) Then
MsgBox "Please enter password.", vbInformation, "Password Required"
Me.txtPassword.SetFocus
Else
'process the job
If (IsNull(DLookup("[UserName]", "tblEmployee", "[UserName] ='" & Me.txtUserID.Value & "' And password = '" & Me.txtPassword.Value & "'"))) Then
MsgBox "Incorrect user name or password."
Else
Me.Visible = False
DoCmd.OpenForm "frmHome"
End If
End If
End Sub

Using Environ("username") will return the value of the current users username. Using environ("userdomain") will return the value of the current users domain.
In your immediate window, do a ?Environ("username") to test and see what you get
On the form where you want users to take ownership, you can have a command button the user clicks to take ownership, you can get the users username from Environ("username") and update the user as the owner in your table.
No need for the logon page (unless you want extra security), your application will always know who the user is.
Also, in your queries that feed your forms, you can have =Environ("username") as the from argument on the username field to show the users the records they own.
HTH

You need to either store the users name in a global variable, or write it to a temporary table.
To store it in a global variable simply declare it in a module
Dim strUser as String
Then modify your login form code like this
If (IsNull(DLookup("[UserName]", "tblEmployee", "[UserName] ='" & Me.txtUserID.Value & "' And password = '" & Me.txtPassword.Value & "'"))) Then
MsgBox "Incorrect user name or password."
Else
Me.Visible = False
strUser=Me.txtUserID.Value
DoCmd.OpenForm "frmHome"
End If
This has the downside of having its value dropped any time a debug/error occurs that is unhandled. It has the upside of being fast and easy to use.
EDIT:
I would go for a local table personally. Make sure you DELETE * FROM tblLocalTableName on application close/logout, and on startup. If you need help with either implementation, let me know.
EDIT:
For a local table, create a table in Access in the frontend file. Lets call it 'tblLocalVars'. Primary key text field, lets name it 'Key', and another text field, let's call it 'Val'. Add a row to this table, Key='LoggedUser' and leave Val empty.
Then on your login form, the code would look something like this:
Private Sub Command1_Click()
If IsNull(Me.txtUserID) Then
MsgBox "Please enter user name.", vbInformation, "User Name Required"
ElseIf IsNull(Me.txtPassword) Then
MsgBox "Please enter password.", vbInformation, "Password Required"
Me.txtPassword.SetFocus
Else
'process the job
If (IsNull(DLookup("[UserName]", "tblEmployee", "[UserName] ='" & Me.txtUserID.Value & "' And password = '" & Me.txtPassword.Value & "'"))) Then
MsgBox "Incorrect user name or password."
Else
CurrentDB.Execute "UPDATE tblLocalVars SET Val='" & Me.txtUserID & "' WHERE Key='LoggedUser'"
Me.Visible = False
DoCmd.OpenForm "frmHome"
End If
End If
End Sub
Now whenever you want to get the current users username, you can use this:
Dlookup("Val","tblLocalVars", "Key='LoggedUser'")
Now you just need to add this to the logout code:
CurrentDB.Execute "UPDATE tblLocalVars SET Val='' WHERE Key='LoggedUser'"
Make sure you add this code to the Unload event on your login form.

Related

How to make a temporary query everytime someone logs in my database?

I'm trying to make it so every time a student logins to this database it creates a query showing their grades by matching up the FullName in the LoginTable and the FullName in the StudentGrades table by DLookup and QueryDef (Which I have little idea on how to use so I probably got it completely wrong). If you know how to fix this, explain QueryDef, or know an easier way to do this than please help me, thanks.
VBA code for login button:
Private Sub Command1_Click()
'If there is no password or username then shows pop-up
'usertext is username box and passtext is password box
If IsNull(Me.usertext) Then
MsgBox "Please enter login", vbInformation, "LOGIN REQUIRED"
Me.usertext.SetFocus
ElseIf IsNull(Me.passtext) Then
MsgBox "Please enter password", vbInformation, "PASSWORD REQUIRED"
Me.passtext.SetFocus
'Sets actual values from table to values started above and checks if username and password actually match up with table
Else
If (IsNull(DLookup("[UserLogin]", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "' and password = '" & Me.passtext.Value & "'"))) Then
MsgBox "Username/password not valid"
'Checks for what securitylvl is the login and sets up studentqry if user is student
Else
Dim SecurityLvl As Variant
Dim StudentName As Variant
Dim StudentQry As QueryDef
SecurityLvl = DLookup("SecurityLvl", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "'")
StudentName = DLookup("FullName", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "'")
If (SecurityLvl = "Admin") Then
MsgBox "Admin Login successful"
DoCmd.Close
DoCmd.OpenForm "AdminForm"
ElseIf (SecurityLvl = "Professor") Then
MsgBox "Teacher Login successful"
DoCmd.Close
DoCmd.OpenForm "TeacherForm"
ElseIf (SecurityLvl = "Student") Then
MsgBox "Student Login successful"
DoCmd.Close
Set StudentQry = DBVeryinitialprototype.CreateQueryDef("StudentQuery", "Select * from StudentGrades where `FullName` = StudentName")
DoCmd.OpenQuery "StudentQuery"
End If
End If
End If
End
End Sub
There is no need for temp queries to be created/deleted with each login. Simply create a permanent query that runs on dynamic data. Specifically, join StudentGrades to LoginTable where the output will be the currently logged in user.
Since your Login process is unclear, possibly you have a status field that identifies which student is in current session (unless you clean out all records in LoginTable each time).
SELECT s.*
FROM StudentGrades s
INNER JOIN LoginTable l
ON l.FullName = s.StudentName
WHERE l.LoginStatus = True
And ideally you join on IDs instead of full string values. Login should have a combobox allowing pick of students with a hidden bound field as ID or retrieve the corresponding StudentID in typed textbox field. This way the StudentQuery would then read:
SELECT s.*
FROM StudentGrades s
INNER JOIN LoginTable l
ON l.StudentID = s.StudentID
WHERE l.LoginStatus = True
How to create a permanent query? This should have been covered in your MS Access 101 course:
Under the Create tab on ribbon, in Queries section click Query Design.
Use either the Design View to create a query with diagram of tables (selecting tables/joins/fields) or SQL View to build queries with SQL.
When finished drafting, click Save. Query should then show up in Navigation Pane.
Currently, you are going the coding route of creating queries with querydefs. But again there is no need to do this dynamically, simply create only one query once and data should align accordingly.

How to use Dlookup in Microsoft access

I am trying to use DLookup to check a text field against a database value except it returns an error when I try to do so. MemberID is the username and is being found using txtUsername field and the password is obviously password which are both retrieved from the Member table.
Here is the code:
Private Sub btnLogin_Click()
If Me.txtPassword.Value = DLookup("[Password]", "Member", "MemberID =
Me.txtUsername.Value") Then
MsgBox "Access Granted", vbInformation, "CD Shop"
MsgBox "Welcome", vbInformation, "CD Shop"
DoCmd.Close
DoCmd.OpenForm "frmGymActivity"
Else
MsgBox "Please re-enter your Username and Password."
End If
End Sub
You need to use proper quoting and string concatenation, to make sure you're passing a string with the value you want.
If Me.txtPassword.Value = DLookup("[Password]", "Member", "MemberID = " & Me.txtUsername.Value) Then
I am assuming MemberID is a number.

in MS ACCESS, is it possible to do: DoCmd.OpenForm "Dlookup...."?

MS Access 2013
I have a tblUser table with following data (UserName / Password / StartForm)
I have a login system in place where user puts in form field called txtLogin his UserName.
After UserName and Password matches, I need to open a specific form for each user (depending on his function in the company).
I have this code in place but can't figure out the problem.
DoCmd.OpenForm DLookup("StartForm", "tblUser","[UserName]='" & txtLogin & "';")
I am only starting programming and I want to learn, not copy/paste code, so I appreciate very much if you can give me a simple explanation.
Thank you
The first parameter to DoCmd.OpenForm is the form name. To open the form to a specific parameter you need to use the
4th parameter which is the WhereCondition.
The Dlookup function is not necessary here. It is used to return a single column from a single record where the sourced column is the first parameter and the source table is the second parameter. It knows what record to grab by the search criteria, the third parameter.
The way you have this set up you are asking DoCmd.OpenForm to open a form by the name of [the result of your DLookup call] with no filter applied.
What you want is more like this
DoCmd.OpenForm NameOfYourUserForm, acNormal, , "[UserName]='" & txtLogin & "'"
I was able to solve the problem as following.
I created a variable for the form I want to call (nomeForm) and I used Dlookup to find appropriate form to each user.
Thank you
Private Sub cmdLogin_Click()
Dim rst As Recordset
Dim nomeUsuario As String
If IsNull(txtLogin) Or IsNull(txtSenha) Then
MsgBox "Preencha o login e senha"
Exit Sub
End If
nomeUsuario = txtLogin
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblUser WHERE UserName = '" & txtLogin & "' AND Password = '" & txtSenha & "';")
If rst.RecordCount = 1 Then
bcansafelyclose = True
DoCmd.Close
Dim nomeForm As String
nomeForm = DLookup("Start", "tblUser", "UserName = '" & nomeUsuario & "'")
DoCmd.OpenForm nomeForm
Else
MsgBox "Login ou senha incorretos"
bcansafelyclose = False
End If
rst.Close
End Sub

Visual basic code for login form in MS Access

I have two fields, username and password, currently there are two users, my code only accepts the 1st user's username and password, but not the second user. Cant seem to figure out where i should make the changes. I get an error in ms access related to duplicate data entry.
Please tell me what i can do to change my code, currently my visual basic code logic is, if username and password are entered correctly then open a form
Private Sub LoginBtn_Click()
Set L = CurrentDb.OpenRecordset("Login")
'validation to check if the user entered the username in the username field
If IsNull(Me.txtUsername) Or Me.txtUsername = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.txtUsername.SetFocus
Exit Sub
End If
'validation to check if the user entered the password in the password field
If IsNull(Me.strPassword) Or Me.strPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.strPassword.SetFocus
Exit Sub
End If
'check to see if the password and username match
If (Me.txtUsername = L.[Username]) And (Me.strPassword = L.[Password]) Then
'Close Member login form and open the member form
DoCmd.OpenForm "Memberform"
Else
MsgBox "Password Invalid. Please try again.", vbOKOnly, "Invalid Entry!"
Me.strPassword.SetFocus
End If
End Sub
It looks like the problem is the last If block: you're opening the Login table (or query?) but you're only looking at the first record, instead of looping through all the records to check if there's a match.
So, you could fix this by changing it to loop through the records until you find a match (not recommended), or you could instead make a query whose criteria are the supplied username and password and see if any records are returned.
Way 1 - looping through records:
Private Sub LoginBtn_Click()
'validation to check if the user entered the username in the username field
If IsNull(Me.txtUserName) Or Me.txtUserName = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.txtUserName.SetFocus
Exit Sub
End If
'validation to check if the user entered the password in the password field
If IsNull(Me.strPassword) Or Me.strPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.strPassword.SetFocus
Exit Sub
End If
'check to see if the password and username match
Set L = CurrentDb.OpenRecordset("Login")
Dim found As Boolean
found = False
If L.BOF And L.EOF Then
MsgBox "There are no usernames or passwords in the database.", vbOKOnly, "No login info"
Exit Sub
Else
Do While Not L.EOF
If (Me.txtUserName = L.[UserName]) And (Me.strPassword = L.[Password]) Then
found = True
Exit Do
End If
L.MoveNext
Loop
End If
If L.EOF And Not found Then
' at the last record and did not find a match
MsgBox "Invalid username or password. Please try again.", vbOKOnly, "Invalid Entry!"
Me.strPassword.SetFocus
' clean up
L.Close
Set L = Nothing
Else
' we found a match; close Member login form and open the member form
' clean up
L.Close
Set L = Nothing
DoCmd.OpenForm "Memberform"
DoCmd.Close acForm, Me.Name
End If
End Sub
Way 2 - a query:
Private Sub LoginBtn_Click()
'validation to check if the user entered the username in the username field
If IsNull(Me.txtUsername) Or Me.txtUsername = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.txtUsername.SetFocus
Exit Sub
End If
'validation to check if the user entered the password in the password field
If IsNull(Me.strPassword) Or Me.strPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.strPassword.SetFocus
Exit Sub
End If
'check to see if the password and username match
' Using a QueryDef with parameters to avoid SQL injection
Dim qdf as DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("","SELECT Username, Password FROM Login WHERE Username=[_uname] AND Password=[_pw]")
qdf.Parameters("_uname") = Me.txtUsername
qdf.Parameters("_pw") = Me.strPassword
Set L = qdf.OpenRecordset
If L.BOF And L.EOF Then
' no match
MsgBox "Invalid username or password. Please try again.", vbOKOnly, "Invalid Entry!"
Me.strPassword.SetFocus
' clean up
L.Close
Set L = Nothing
Else
' we found a match; close Member login form and open the member form
'clean up
L.Close
Set L = Nothing
DoCmd.OpenForm "Memberform"
DoCmd.Close acForm, Me.Name
End If
End Sub

Creating a login form in Microsoft Access using macros, without VBA.

I've looked around for ages and I haven't found an answer to my problem so I was hoping someone here could help me.
I am creating a system using Microsoft Access where I have a members table containing a username and password and various other fields such as date of birth, etc.
I want to create a form where users can enter a username and password. By clicking a button on this form, these details will then be checked against the usernames and passwords in the members table. If the details match, a message will be displayed saying they have logged in. If the details are not found in the table, a message saying the details are incorrect will show.
How can I do this without using VBA?
I have started by creating a form called loginform with two text boxes loginusername and loginpassword.
Where should I go from here?
The VBA solution shouldn't be that complicated. A quick and dirty solution:
Dim Result as Variant
Result=Dlookup("Password","tblMembers","UserName='" & nz(loginusername.value,"") & "'")
If nz(Result,"")<>nz([login password].value,"") Then
MsgBox "Invalid password"
Else
MsgBox "Password correct"
End If
'set the variables
Dim UN As String
Dim PW As String
Dim user, pass As Boolean
'make sure none of the fields are null, or blank
UN = Text
PW = Text
If IsNull(Username) Then
MsgBox "You must enter a username."
Username.SetFocus
Else
'assign true to user
user = True
End If
If IsNull(Password) Then
MsgBox "You must enter a password."
Password.SetFocus
Else
pass = True
End If
If user = True And pass = True Then
UN = DLookup("[Username]", "LoginTable", "[Username]= '" & Me.Username & "'")
PW = DLookup("[Password]", "LoginTable", "[Password] = '" & Me.Password & "'")
End If
If Me.DummyUser = Me.Username And Me.DummyPass = Me.Password Then
MsgBox "Access granted."
Else
MsgBox "Access denied."
End If