Open Automatically Specified Form When I am Open Access (1 Viewer)

Bandara

Member
Local time
Tomorrow, 04:34
Joined
Apr 17, 2020
Messages
40
I created Access Database with Forums. And I created Login Form Also. When I Open My Access File First automatically it ask to Login. It's Ok.
Now I want to do it when i am Input correct user name and password I want to open automatically Onther Form. How to do it? Here is the Code in Login Button

Private Sub cmd_login_Click()

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String

If Trim(Me.txt_username.Value & vbNullString) = vbNullString Then
MsgBox prompt:="Username should not be left blank.", buttons:=vbInformation, title:="Username Required"
Me.txt_username.SetFocus
Exit Sub
End If

If Trim(Me.txt_password.Value & vbNullString) = vbNullString Then
MsgBox prompt:="Password should not be left blank.", buttons:=vbInformation, title:="Password Required"
Me.txt_password.SetFocus
Exit Sub
End If

'query to check if login details are correct
strSQL = "SELECT FirstName FROM tbl_login WHERE Username = """ & Me.txt_username.Value & """ AND Password = """ & Me.txt_password.Value & """"

Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL)
If rst.EOF Then
MsgBox prompt:="Incorrect username/password. Try again.", buttons:=vbCritical, title:="Login Error"
Me.txt_username.SetFocus
Else
MsgBox prompt:="Hello, " & rst.Fields(0).Value & ".", buttons:=vbOKOnly, title:="Login Successful"
DoCmd.Close acForm, "frm_login", acSaveYes
End If

Set db = Nothing
Set rst = Nothing

End Sub
 

Minty

AWF VIP
Local time
Today, 23:04
Joined
Jul 26, 2013
Messages
7,502
Simply open the form you want? After this line (the Save is unnecessary - it's for saving form design changes not data)
DoCmd.Close acForm, "frm_login"
add this line
DoCmd.OpenForm "YourFormNameGoesHere"
There are switches you can use on the form opening- read up here;
 
Last edited:

Micron

AWF VIP
Local time
Today, 18:04
Joined
Oct 20, 2018
Messages
3,471
Bandara, please post anything more than a few lines of code within code tags (Insert on forum menu bar) to make it easier to read. One thing about your current approach: it is good that you realized the need to SET things to Nothing, but do you realize that if you simply Exit Sub then those lines don't get processed? I don't wish to reopen the debate around here as to whether or not that has any negative effect - just wanted to point out that you want to watch out for proper code execution when creating objects and some types of variables. Two other observations:
- you don't need .Value as it is the default property of data controls
- you could do this with DLookups rather than creating db, rs objects. Not that your way is wrong; it's just a bit more complicated.
 

Users who are viewing this thread

Top Bottom