Currently have a database containing the location of devices, and a form used to update the location of the devices and save a copy of their previous location. Ideally want to be able to input a list of "BoxNo" values (the ID field) and run the form multiple times with the same update on each record. Is this possible with VBA/SQL? Very low level of programming knowledge, any help would be much appreciated.
EDIT: As requested by Gord Thompson, clarification on the form procedure.
On the form there is a boxnumber textbox, which is locked and changed only by using the search bar at the bottom of the page i.e in the navigation pane part, not the form itself, and a few text and comboboxes which correspond to fields related to the boxnumber. The user changes the relevant fields and then clicks an "update" button which runs the following code (The part relevant to the question is after the else statement).
Private Sub Update_Click()
'checks whether date updated
If DateUpdated = False Then
MsgBox "Please enter a date", vbOKOnly, "Enter Date"
'saves copy to "changes" table
Else
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Change_In_Location_tbl (Sm_ID,Given_To,On_Date, Comments) VALUES ( " & Sm_ID.OldValue & ",'" & Currently_Held_by.OldValue & "','" & Date_Given.OldValue & "','" & Comments.OldValue & "');"
DoCmd.SetWarnings True
MsgBox "Update Complete", vbOKOnly
End If
End Sub
Sounds like you want to use a Do While loop. Assuming you have the list of values in a table, open the recordset and loop through each value.
Dim db as Database
Dim rec as Recordset
set db = CurrentDB
set rec = db.OpenRecordSet ("Select * from MyTableWithBoxNoValues")
Do while rec.EOF = False
... process the BoxNo and save it
(i.e., whatever your form is currently doing...)
rec.MoveNext
Loop
Related
Okay, I am having difficulties coding security behind my user form. Let me give you guys the rundown. I created this make table "tblPermissionTypes" that basically has two field in there "ID" & "EmployeeType_ID". The ID field represents Security level of access 0 through 2, and EmployeeType_ID is the title: 0 = Requestor, 1 = Admin, and 2 = Printer.
With that being said I have another table "tblEmployees" with the same field "EmployeeType_ID", I manually set the 0s, 1s, & 2s. This table also contains all employees UserNames
Finally, I have another table "tblPermission" that contains three fields "EmployeeType_ID", "FormName", and "HasAccess"
My end result is being whenever this tblPermission has a Checkbox under the field HasAccess I want to grant access based on the EmployeeType_ID field to communicate back to the table "tblEmployees", but in this case I want them to only be able to see a button that contains that certain form.
Private Sub cmdClick_Click()
Dim strSQL As String
Dim permission As String
If permission = ("fOSUserName") = True Then
Run strSQL
strSQL = "SELECT * FROM tblEmployees WHERE "
strSQL = strSQL & "tblEmployees.Five2 =" & ("fOSUserName") & """, = False
Then
MsgBox "You do not have permission!", vbExclamation
Else'
cmdButton.Visible True
End If
NOTE: fOSUserName, is a function I created basically the same thing as
Environ("UserName")
Debug.Print strSQL
Function calls should not be within quote marks. You construct an SQL statement but then don't properly use it. You declare and use variable permission but don't set the variable - it is an empty string. Need form name as a search criteria. Couple of other syntax errors but they will go away with this suggested code. Run this code in form Open event to disable button and don't even give unauthorized users opportunity to click. Don't annoy them with a popup message that emphasizes their lowly status in hierarchy.
You need to build a query that joins tblEmployees to tblPermission so that UserName, FormName, HasAccess fields are all available then reference that query in search for permission.
A DLookup could serve here.
Me.buttonNameHere.Visible = Nz(DLookup("HasAccess", "queryNameHere", _
"UserName='" & fOSUserName & "' AND FormName='FormNameHere'"), 0)
The problem I'm facing:
I try to check if inserted text from multiple text boxes is already existing in a table before saving the records to avoid duplicates.
I created a form to enter new members and save them into a table. The key to avoid duplicates is to check the combination of given name, last name and birth date with existing records. (It's most likely that there won't be two person with all three criteria matching)
I have no problem to check the existence for only one text box by setting the focus on the desired box and use the SQL query IF EXISTS...
But since I would need to set focus on several text boxes(IMO) the problem occurs.
Is there a way to set focus on multiple text boxes?
The idea would be to use an IF EXISTS...AND EXISTS statement and I would need to implement the .SetFocus statement for each text box before checking its existence.
I hope you get my point and I would be glad if someone could share some knowledge. :)
Thanks in advance
There seems to be some missing information in order to find the best solution to your problem. so the below response will be based on assumptions as to how your form is working.
I'm assuming you are using an unbound form with unbound text boxes? if this is the case, then you must have a button that is the trigger for checking/adding this information to your table. lets say your command button is called "Save". You can use the following code without the need to .setfocus to any textbox.
Private Sub Save_Click()
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
set db = currentdb 'This is the connection to the current database
'This is the SQL string to query the data on your table
strsql = "SELECT * " & _
"FROM [Yourtablename] " & _
"WHERE ((([YourTableName].[FirstName]) ='" & me.FormFirstNameField & "' AND ([YourTableName].[LastName]) ='" & me.FormLastNameField & "' AND ([YourTableName].[DOB]) =#" & me.FormDOBField & "#));"
set rst = db.openrecordset(strsql) 'This opens the recordset
if rst.recordcount <> 0 then
'Enter code to inform user information already exists
else
'Enter code if information does not exits
end if
rst.close 'Closes the recordset
set rst = nothing 'Frees memory
set db = nothing 'Frees Memory
End Sub
Let me know if this code works or if I need to make changes based on your scenario.
I'm using bound forms for the user to update information on new or existing customers. Right now I'm using a Add New Record macro on the submit button (because I'm not sure how to add or save a new record through VBA).
I added a before update event (using VBA) to have the user confirm they want to save changes before exiting the form. For some reason this is overriding the add record button and now users cannot add new record until exiting the forms.
How can I use VBA to add new customer information to the correct table? Is this something that should be done with macros instead?
Form BeforeUpdate Code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strmsg As String
strmsg = "Data has been changed."
strmsg = strmsg & " Save this record?"
If MsgBox(strmsg, vbYesNo, "") = vbNo Then
DoCmd.RunCommand acCmdUndo
Else
End If
End Sub
Add Record Button:
Private Sub btnAddRecord_Click()
Dim tblCustomers As DAO.Recordset
Set tblCustomers = CurrentDb.OpenRecordset("SELECT * FROM [tblCustomers]")
tblCustomers.AddNew
tblCustomers![Customer_ID] = Me.txtCustomerID.Value
tblCustomers![CustomerName] = Me.txtCustomerName.Value
tblCustomers![CustomerAddressLine1] = Me.txtCustomerAddressLine1.Value
tblCustomers![City] = Me.txtCity.Value
tblCustomers![Zip] = Me.txtZip.Value
tblCustomers.Update
tblCustomers.Close
Set tblCustomers = Nothing
DoCmd.Close
End Sub
In order to submit a record using VBA, create an On Click event for the button, and in that Sub run the following command:
Private Sub submitButton_Click()
'All the code to validate user input. Prompt user to make sure they want to submit form, etc.
DoCmd.RunSQL "INSERT INTO tblCustomers (CustomerID, CustomerName, CustomerAddressLine1, City, Zip) values (txtCustomerID.Value, txtCustomerName.Value, txtCustomerAddressLine1.Value, txtCity.Value, txtZip.Value)"
End Sub
In this Sub, you can add all the code you want to validate the values that the user entered and choose whether or not you want to submit the record. There's a lot of control using VBA to submit your forms, so you do not need a BeforeUpdate event.
Also, do NOT use bound forms with this method. I don't know what the repercussions are but I wouldn't try it. Access is great for starting off, but as you want to do more complex things, it is easier to just use VBA.
It seems strange that you would create a before update event for your form to create a prompt before closing. Perhaps you should try the on close event instead. If you want to use vba to add a new record from the form you can simplify your statement. I came across a similar situation when designing my own form for my Access DB. This code is tested and working:
Dim sVIN As String
Dim sMake As String
Dim sModel As String
Dim sColor As String
Dim sType As String
Dim intYear As Integer
sVIN = Me.txtVIN.Value
sMake = Me.txtMake.Value
sModel = Me.txtModel.Value
sColor = Me.txtColor.Value
sType = Me.comboType.SelText
intYear = Me.txtVehicleYear.Value
DoCmd.RunSQL "INSERT INTO Vehicles (VIN, Make, Model, VehicleYear, Color, Type) VALUES ('" & sVIN & "', '" & sMake & "', '" & sModel & "', " & intYear & ", '" & sColor & "', '" & sType & "')"
If you are just using one DB in your project and you're connecting on start up you can sometimes run simple DoCmd.RunSQL statements like this. You can take the syntax here and adapt it to your own project. I myself got the basic syntax from W3 schools. Good site for learning to write SQL queries. It should also be noted that validation testing is not included here. You should make sure it is included in the form validation rules or in vba code. One more thing... in your SQL it looks like you are attempting to assign a value to the ID column from a text box entry; if ID is an auto number column, don't do this. ID columns are usually assigned a number automatically, so you don't need to (or want to) specify an insert value for that.
As a side note:
I noticed that adding records via VBA functionality(as in your "Add Record Button" code) works ~400 times faster than using DoCmd.Run SQL "INSERT INTO...":
~55k records/s compared to 140 records/s for a table with 5 columns(ID+4 short strings).
This has no practical meaning in terms of a form, where data is entered manually but if the form is generating more records, this saves a lot of time.
I am trying to run a query in Access 2010 inside of a form. The form, per user request, needs to have buttons that they can use to quickly change the data in their column. For the table being called, there are only two columns that matter: Equiptment_Name and Amount (The other several columns are just there to help reference the data in case they misspell the name of the product). The current query I have is:
UPDATE tblInventory SET Amount = Amount-[Enter Amount]
WHERE ((([tblInventory].Equiptment_Name)=[Enter Name]));
This works perfectly, I just can't get it to work in a form with a button. I've searched all over for help and was encouraged to use a macro because that would be the easiest way. Can someone please walk me through the process of getting a macro to run a version of my query? I'm fine with the user being prompted to enter the amount to withdraw from the Amount category, but it would be nice if they didn't have to type in the Equiptment_Name category since The button would be in the form next to it (see picture below). Thanks for all help in advance.
You could simply use VBA to get this going. Something along the lines of
Private Sub Command70_Click()
If Len(Me.AmountTextBoxName & vbNullString) = 0 Then
MsgBox "Amount cannot be empty !", vbCritical
Exit Sub
End If
If Len(Me.Equiptment_NameTextBoxName & vbNullString) = 0 Then
MsgBox "Equiptment Name cannot be empty !", vbCritical
Exit Sub
End If
CurrentDB.Exeucte "UPDATE tblInventory SET Amount = Amount - " & Me.AmountTextBoxName & _
"WHERE tblInventory.Equiptment_Name = '" & Me.Equiptment_NameTextBoxName & "';"
End Sub
I have taken the Equipment name is actually a String.
I'm working on running an append query (to change someones login password) in access, currently it checks to make sure the password matches and that they knew the original password. However, I run into a problem where if the update query: DoCmd.RunSQL "UPDATE Credentials SET Credentials.[Password] = [Forms]![LoginSubmit]![DesiredPassword] WHERE (((Credentials.Password)=[Forms]![LoginSubmit]![CurrentPassword]) AND ((Credentials.[User ID])=[Forms]![LoginSubmit]![User ID]));" updates 0 rows (meaning that the conditions were not met) it closes (I have a docmd.close following). If it does update their password it does the same, so in the end you don't know if it was successful until you try your new password.
I would like to know when it updates 0 rows so I can shoot up a MsgBox telling them it didn't work, end the sub and have them try again. If it updates 1 row I would have a MsgBox say "Success".
I know the VBA to the above except for the part that returns a value for the amount of updated rows in that query. Could someone help me out?
Thanks in advance.
Execute your UPDATE statement from a DAO.Database object variable. Afterward you can base your user notice on the variable's RecordsAffected property.
Here is a simple example, verified with Access 2007.
Dim db As DAO.Database
Dim strUpdate As String
strUpdate = "UPDATE tblFoo" & vbCrLf & _
"SET some_text = 'bar'" & vbCrLf & _
"WHERE id = 7;"
Debug.Print strUpdate
Set db = CurrentDb
db.Execute strUpdate, dbFailOnError
MsgBox db.RecordsAffected & " records affected"
Set db = Nothing