Passing a variable from one form to another - vba

I created a login screen for my DB which works.
I would like to pass a variable to a text box that will be on the 'Main Menu' form once you're validated.
Here's my code when you click 'Login'.
'Login button submit, validate, welcome message & main menu navigation
Private Sub cmd_login___Click()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
'query to check if login details are correct
strSQL = "SELECT Name FROM LoginQuery 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
DoCmd.Close
DoCmd.OpenForm "MainMenu"
End If
Set db = Nothing
Set rst = Nothing
This line displays a prompt on screen saying Login successful with the "rst.Fields(0).Value" variable which is the users full name, but I'd prefer less windows and buttons to press and instead, pass this variable to a new blank form with a textbox on it.
MsgBox prompt:="Hello, " & rst.Fields(0).Value & ".", buttons:=vbOKOnly, title:="Login Successful"
I named the textbox on the MainMenu form, txt_welcome.
I tried appending the below in the IF statement:
Dim name As String
name = "SELECT Name FROM LoginQuery WHERE Username = """ & Me.txt_username.Value & """ AND Password = """ & Me.txt_password.Value & """"
[MainMenu]![txt_welcome].Value = name
[MainMenu]![txt_welcome].Value = "dsfadsf"
MainMenu!txt_welcome.value = "justdisplaysomethingplz"

You can pass it through the OpenArgs parameter of the DoCmd.OpenForm method.
DoCmd.OpenForm "MainMenu", OpenArgs:="Something"
Then, on the MainMenu form, read its value when the form loads:
Private Sub Form_Load()
If Not IsNull(OpenArgs) Then Debug.Print OpenArgs
End Sub

Related

VBA code works in one box, throws an error in another

Alright, short background, I have a form, on which I have 3 Comboboxes.
Two of these comboboxes are tied to the same exact table, an accounts table. They use slightly different queries between them, see below.
In one box, cmb_GA I have set the box property "On Not in List" to the following code segment :
Private Sub cmb_GA_NotInList(NewData As String, Response As Integer)
Dim cnn As New ADODB.Connection
Dim strSQL As String
Dim password As String
Dim bytUpdate As Byte
On Error GoTo ErrHandler
Set cnn = CurrentProject.Connection
bytUpdate = MsgBox("Do you want to add " & NewData & " to the Accounts list?", vbYesNo, "Not in list of Accounts!")
If bytUpdate = vbYes Then
password = InputBox("Enter New Account Password")
strSQL = "INSERT INTO tbl_Accounts(Login, PW) " & "VALUES
('" & NewData & "#mcsnet.org' , '" & password & "')"
Debug.Print strSQL
cnn.Execute strSQL
Response = acDataErrAdded
Call AuditLogs("txt_DN", "New")
ElseIf bytUpdate = vbNo Then
Response = acDataErrContinue
Me!cmb_GA.Undo
End If
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
End Sub
Note that for formatting here I put in an extra CR after "VALUES" that doesn't exist in the actual code, other than that, and some deleted comments, WYSIWIG.
This code works perfectly. 100% Does what I want.
I have another combobox, cmb_IA
I am using the same code for it (Yeah I probably should have done this as a module in retrospect, but I didn't yet.)
The problem is that it throws an error. "The text you entered isn't an item in the list. Select an Item from the list, or enter text that matches one of the listed items."
I've looked at the properties and can not find a difference between the two boxes on the property sheets: Here's a look at both boxes Data tab:
And here is the relevant SQL from the two queries:
SELECT *
FROM tbl_Accounts
WHERE tbl_Accounts.Association LIKE "*Device*";
and
SELECT *
FROM tbl_Accounts
WHERE tbl_Accounts.Association LIKE "*Intune*";
I would assume the question is obvious, but let me state this outright, what is happening here? Is there a way to suppress this error? Both comboboxes must let the user add new information to them, as the point of this form is to register new devices, cellphones and tablets, and the security accounts and corporate accounts that each device uses. What's puzzling me the most is that this error is only showing up on the one combobox.
Edited to add the code from the section that is throwing the error:
Private Sub cmb_IA_NotInList(NewData As String, Response As Integer)
Dim cnn As New ADODB.Connection
Dim strSQL As String
Dim password As String
Dim bytUpdate As Byte
On Error GoTo ErrHandler
Set cnn = CurrentProject.Connection
bytUpdate = MsgBox("Do you want to add " & NewData & " to the Accounts list?", vbYesNo, "Not in list of Accounts!")
If bytUpdate = vbYes Then
password = InputBox("Enter New Account Password")
strSQL = "INSERT INTO tbl_Accounts(Login, PW) " & "VALUES ('" & NewData & "#mcsnet.org' , '" & password & "')"
Debug.Print strSQL
cnn.Execute strSQL
Response = acDataErrAdded
Call AuditLogs("txt_DN", "New")
ElseIf bytUpdate = vbNo Then
Response = acDataErrContinue
Me!cmb_IA.Undo
End If
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
End Sub
It was suggested I show the RowSource SQL generated by Access so here it is Working:
SELECT qry_DeviceAccounts.AccountIDKey, qry_DeviceAccounts.Login, qry_DeviceAccounts.PW
FROM qry_DeviceAccounts
ORDER BY qry_DeviceAccounts.[Login];
Not Working:
SELECT qry_SecurityAccounts.AccountIDKey, qry_SecurityAccounts.Login, qry_SecurityAccounts.PW
FROM qry_SecurityAccounts
ORDER BY qry_SecurityAccounts.[Login];
I can't believe I didn't see it earlier. This was the result of the difference between the two queries, and the way they filtered for the account information. I needed to set the new account information to be filtered for during the INSERT statement, which hadn't been done. Since the other one worked on the default value of one of the fields in the table, it wasn't relevant to that one's INSERT statement.
Moral of the story, check your fields, and make sure you carefully read what each is doing. I was so busy looking for an error in my VBA, I forgot to check my SQL.

Runtime Error 15 - Type Mismatch for code to change a password in MS Access database

I get a Runtime Error 15 on the following line:
MyuserID = Me.txtfirstname.Value from the code below:
Option Compare Database
Option Explicit
Private Sub cmdchange_Click()
On Error Resume Next
If Trim(Me.txtnewpass & "") <> Trim(Me.txtconfirmpass & "") Then
MsgBox "Passwords do not match", vbExclamation + vbOKOnly, ""
Me.cmdchange.Enabled = False
Else
Me.cmdchange.Enabled = True
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select' From[User Registration Details] where [UserID]=" & MyuserID)
If Not rs.EOF And Not rs.BOF Then
rs.Edit
rs("Password") = txtconfirmpass
rs.Update
rs.Close
Set rs = Nothing
MsgBox "Your Password has been successfully changed", vbInformation, "Electporl"
DoCmd.Close acForm, "frmnewpassword", acSaveNo
DoCmd.OpenForm "frmlogin"
End If
End If
Given that I placed the code below on the button that takes the user to the changing password form.
Private Sub cmdproceed_Click()
If IsNull(Me.txtfirstname) Or Me.txtfirstname = "" Then
Me.mand1.Visible = True
Me.txtfirstname.SetFocus
End If
If IsNull(Me.txtemail) Or Me.txtemail = "" Then
Me.mand2.Visible = True
Me.txtemail.SetFocus
End If
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("User Registration Details", dbOpenSnapshot, dbReadOnly)
rs.FindFirst ("Firstname='" & Nz(Me.txtfirstname, "") & "'")
If rs.NoMatch = True Then
Me.lbl1.Visible = True
Me.txtfirstname.SetFocus
Exit Sub
End If
If rs!Username <> Nz(Me.txtemail, "") Then
Me.lbl2.Visible = True
Me.txtemail.SetFocus
Exit Sub
End If
'MyuserID is publicly declared as Long in a module
MyuserID = Me.txtfirstname.Value
DoCmd.OpenForm " frmnewpassword"
DoCmd.Close acForm, Me.Name
End Sub
the second code is assigned to the button that redirects the user to the form that will enable him or her change the password after verifying his or her first name and email.
The second one now is assigned to the button that will help the user change the password by overwriting the old password.
Please pass the UserID value in your procedure.
In your cmdproceed_Click() procedure update the following section:
'MyuserID is publicly declared as Long in a module
MyuserID = rs("UserID")
In your cmdchange_Click() procedure update the following line:
Set rs = CurrentDb.OpenRecordset("Select * From [User Registration Details] where [UserID]=" & MyuserID)
From a logical point of view, you can have others with the same firstname, so doing the filter on the firstname only will introduce unexpected behaviors later in the life cycle of your application.
If you have two or more users with the first name 'Joshua' then your code will always select the first user with that first name. You need to update this logic to select a unique user.

How do you go to a specific record chosen from a listbox and displayed on the navigation form?

I have a navigation form which has a subform with a recordsource tblA.
Currently, the subform displays the specific record in popup window. Is it possible for it to display the record in the navigation form without having to pop up?
Private Sub Search_Change()
Dim where As String
Const SQLResults As String = "SELECT itemNumber, itemName FROM tblMain "
<whereclause> ORDER BY ItemName;"
If Me.Search.Text <> "" Then
where = "WHERE itemName LIKE '*" & Me.Search.Text & "*' "
End If
Me.SearchResults.RowSource = Replace(SQLResults, "<whereclause>", where)
End Sub
The below code displays the record in a pop-up window.
Private Sub SearchResults_Click()
Dim searchCriteria As String
searchCriteria = "[itemNumber]='" & Me![SearchResults].Value & "'"
DoCmd.OpenForm "frmDisplay", acNormal, , searchCriteria
DoCmd.Close acForm, "frmSearch"
End Sub
Since form frmNavigation is always open:
Private Sub SearchResults_Click()
DoCmd.OpenForm, "frmDisplay", acNormal, , searchCritera
DoCmd.Close acForm, "frmSearch"
End Sub
Can someone help?
I have done it! I hope this solution helps someone. The code allows the user to select the item in a listbox on a pop-up form and takes the user to that same record on the navigation form. It makes the forms operation simpler without popping up the subform. Note: You do not need to set pop-up feature on the property sheet to false. It will work regardless.
Private Sub SearchResults_Click()
Dim searchCriteria As String
Dim rs As Recordset
searchCriteria = "[itemNo]='" & Me![SearchResults].Value & "'"
Set rs = Forms!frmNavigation!NavigationSubform.Form.RecordsetClone
rs.FindFirst searchCriteria
If Not rs.NoMatch Then Forms!frmNavigation!NavigationSubform.Form.Bookmark = rs.Bookmark
Forms!frmNavigation!NavigationSubform.Form.Filter = "[itemNo]=" & Me.SearchResults.Value
Me.FilterOn = True
Set rs = Nothing
DoCmd.Close acForm, "frmSearch"
End Sub

How to look up data in an Access table using the UserName Environ

In MS Access, I have a table named "Table" with three fields. Besides the ID field, I have one field named "User" and one field named "Email". Both fields are "short text". The table has two rows, the first: User = Nobody and Email = nobody#yahoo.com. The second: User = Somebody and Email = somebody#aol.com.
I've created a Module with the following code:
Sub Test()
Dim rs As Recordset
Dim localUser As String
localUser = Environ("UserName")
Set rs = CurrentDb.OpenRecordset("Table", dbOpenDynaset)
rs.FindFirst "[User] = 'localUser'"
MsgBox rs![Email]
End Sub
The local user is "Somebody" as shown when performing a: MsgBox Environ("UserName")
When I execute the code, I get a message box with "nobody#yahoo.com".
What I am trying to get is a message box with "somebody#aol.com".
What am I doing wrong?
Thank you in advance.
Try with:
rs.FindFirst "[User] = '" & localUser & "'"
But you could use DLookup:
Dim localUser As String
localUser = Environ("UserName")
MsgBox Nz(DLookup("[Email]", "Table", "[User] = '" & localUser & "'"))

Access, VBA: Find First not working correctly

I hope this is a simple question for someone. I have this method that uses two form fields to check if a record exists in my table and either adds a record or does nothing. So if patient_id is 100, and visit_number is 1, then I will only add a new record if it doesn't already exist.
So, if rst.NoMatch is true - add a new record. However, I can't get it to recognize a duplicate. Here is the code:
Private Sub add_record_button_Click()
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
Dim dbs As DAO.Database
Set dbs = CurrentDb
If IsNull(Form.patient_id) Or IsNull(Form.visit_number) = True Then
MsgBox "Please fill in both fields."
Else
rst.FindFirst "[patient_id] = " & Form.patient_id & " And [visit_number] = " & Form.visit_number
If rst.NoMatch Then
Set rst = dbs.OpenRecordset("Visits")
rst.AddNew
rst!patient_id = Form.patient_id
rst!visit_number = Form.visit_number
rst.Update
MsgBox "New patient visit has been added to the database."
Else
MsgBox "That visit already exists."
End If
rst.Close
End If
End Sub
I believe that my FindFirst line isn't correct. In the database, the variables are named patient_id and visit_number. On the form they are named the same.
Any help would be appreciated, thanks.
EDIT.
From the comments below, I was able to get my logic working but using a different compare feature, Dlookup.
IsNull(DLookup("[patient_id]", "MyTable", "[patient_id] = " & Forms("MyForm").patient_id & " AND [visit_number] = " & Forms("MyForm").visit_number)
FINAL EDIT.
The above line made everything work if I used the form directly, however if I put the form into a navigation form - it stopped working. The string that ultimately got it working from within a navigation form looks like this:
If IsNull(DLookup("[patient_id]", "Visits", "[patient_id] = " & Me!patient_id.Value & " AND [visit_number] = " & Me!visit_number.Value)) = True Then
Thank you all for your help.
I've never seen Form used this way, and you should be able to add the record directly in the form, so try:
Private Sub add_record_button_Click()
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
Dim PatientId As Variant
Dim VisitNumber As Variant
PatientId = Me!patient_id.Value
VisitNumber = Me!visit_number.Value
If IsNull(PatientId) Or IsNull(VisitNumber) Then
MsgBox "Please fill in both fields."
Else
rst.FindFirst "[patient_id] = " & PatientId & " And [visit_number] = " & VisitNumber & ""
If rst.NoMatch Then
rst.AddNew
rst!patient_id.Value = PatientId
rst!visit_number.Value = VisitNumber
rst.Update
MsgBox "New patient visit has been added to the database."
Else
MsgBox "That visit already exists."
Me.Bookmark = rst.Bookmark
End If
End If
End Sub