I'm trying to create a simple form using unbound combo boxes and a button that updates a table when clicked. I have already created another form that is similar to this that works great, so I tried to replicate it using the appropriate fields, but I get an error message- Run-time error '3061: Too few parameters. Expected 1.
The only two fields on the form are FrameID and FrameLocation and the button is MoveFrame. The table to be updated is StockFrames.
This is the code I have on the on-click event on the button:
Private Sub MoveFrame_Click()
CurrentDb.Execute "UPDATE StockFrames SET frameLocation = " & Me.frameLocation & _" WHERE FrameID = " & Me.FrameID
Me.frameLocation.Value = Null
Me.FrameID.Value = Null
End Sub
I appreciate any help anyone can offer. I'm very new to MS Access. If there is any other information that you need as far as the property settings, please let me know. I'm eager to learn and to get this form working properly.
Thank you.
If frameLocation is a text field, parameter needs apostrophe delimiters:
='" & Me.frameLocation & "' WHERE.
Remove that underscore character.
Date/Time fields use # delimiter.
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 have inherited a Microsoft Access 2010 database that is used to keep position/employee information in a single table. The table has an auto-number field for each record. The database has a form – ScreenB – that uses a query to pull and display in ScreenB a single record based on search criteria (Personnel Number, Last Name, Social Security Number, etc.) entered by the user. The record contains approximately 25 fields that show the information about the position as well as information about the person in the position. Of course, every so often a person will leave a position and someone else will be hired into the vacated position. My users would like a button on ScreenB that will, when clicked:
Copy the record information displayed in the form for just the 12 or so fields of position information being displayed on ScreenB.
Paste the information as a new record in the table.
Display the new record with the pasted information in the form.
Since the query pulls a single record, my thought was to create a new form – ScreenC – identical in all respects to ScreenB to display the new record. So, the button will copy the position information from the record displayed on ScreenB, paste it as a new record into the table, open ScreenC, jump to the end of the records in the table and display the new (last) record (which contains only the position information) on ScreenC, and close ScreenB, leaving the user with the position information only and a form that can be filled out with the employee information. This will preserve the information of the previous employee while in that position, which is required.
I’m not a trained programmer, so the code below is probably rife with errors, but it was the best I could come up with:
Dim strSQL as String
strSQL = "INSERT INTO [tblNewCurrent Emp] (numCostCenter, numPosition, txtTitles, txtClassCode. numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified) "
strSQL = strSQL & "SELECT numCostCenter, numPosition, txtTitles, txtClassCode. numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified from [tblNewCurrent Emp] "
strSQL = strSQL & "WHERE (numSystemNumber = " & Me.numSystemNumber & ")"
DoCmd.RunSQL (strSQL)
DoCmd.OpenForm frmScreenC
DoCmd.GoToRecord , , acLast
DoCmd.Close frmScreenB
The table is named “tblNewCurrent Emp”, which is why I placed it in brackets. numSystemNumber is the name of the auto-number field. All forms, queries and tables are in a single database/file. The field names in the code above are the actual names of the fields.
When I attempt to run the code, I get an error message that states, “Syntax error in INSERT INTO statement.” No other information, and no information in the Access Help system. I tried removing the brackets from the table name, and get the same error message. I would appreciate any input, thoughts, or suggestions. What is the error with the INSERT INTO statement? Is there another way to accomplish this task? Unfortunately, I can’t make structural changes to the database and since it is the backend for a number of other databases, changing the table name is not an option, either. Users access the database through the forms only. No datasheet or other views. Thanks.
EDIT: Thank you billmac1 and Remou. The "...,txtClassCode. numGrade,..." was the issue on the SQL. Once I corrected that, I used your suggestion to run the code in the Immediate Windows with the print.debug as well. Ran fine, so all that was left was to clean up the VBA code for opening and closing the forms. For anyone else attempting the same, I also set ScreenC to open to the last record in the Load property. It works perfectly now. Below is the finished code.
Dim strSQL As String
strSQL = "INSERT INTO [tblNewCurrent Emp] (numCostCenter, numPosition, txtTitles, txtClassCode, numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified) "
strSQL = strSQL & "SELECT numCostCenter, numPosition, txtTitles, txtClassCode, numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified FROM [tblNewCurrent Emp] "
strSQL = strSQL & "WHERE (numSystemNumber = " & Me.numSystemNumber & ")"
DoCmd.RunSQL (strSQL)
DoCmd.OpenForm "frmScreen C"
DoCmd.Close acForm, "frmScreen B"
Too new to this site to leave this one as a comment, but part of your SQL string caught my attention "...,txtClassCode. numGrade,...". There's a period and a space in both your field string and value string.
As Remou suggested, "...try a debug.print strSQL and paste the result into the query design window to check for problems." You might also find it beneficial to just take the SELECT portion of your statement and get it working, then try the INSERT portion.