MS Access SQL to copy part of a record displayed on a form, insert into same table as new record, and display the new record on a form - sql

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.

Related

Is there a simple code to allow certain user(s) access to see command buttons?

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)

append data from form to column

I am working on a "issue tracker" access data base where the user enters there data through forms, create new form and edit form.
I have a comment section on my edit form which I have been requested to remained lock, for viewing purposes. So the user can only view the comments.
I have another box below that must "append" or add data to the comment section with a time and user stamp.
My approach is to create a vba code that will allow the user to enter data, and once entered will show in the locked comment section. As the user is working through a "editing" form.
I am fairly new to access and vba and unfortunately I cant find anything that I understand online.
Below is some code use and found searching online. I have but can figure out how to append ( or add ) it to the existing column. It is running fine but the data value I wish to add don't go anywhere?
Private Sub Add_Click()
Dim StrSQL As String
Dim addComments As String
' where addcomment.value is the value desire to append
addCommentStr = Me!addComment.Value
'where IssueTrack is Table, AdditionalComments is column
StrSQL = "INSERT INTO IssueTracker(AdditionalComments) VALUES ('" &
addCommentStr & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
MsgBox ("Comment Added")
End Sub
You wouldn't just keep on appending text to the same record. Where would you end?
So, skip all the code and create a form bound to the table.
Have one field for the date. Set its DefaultValue to: Now()
Set the form's property AllowEdits to: False

MS Access Issue

Hello Stackoverflow community!
I have run into an issue and I'd love some advice.
I'm working with MS Access and I am trying to append two particular fields from one table to another; however this implementation is in a form and it gets a little complicated... So, I'll explain everything the best that I can
BACKGROUND INFORMATION:
First and fore most, I have two tables; one of which is a linked excel spread sheet from another directory (who is not willing to change any formatting what so ever, so I CANNOT make ANY changes to this file and it is being updated on a daily basis). This excel spreadsheet is very large and contains somewhere around 50 columns
The other table is not anywhere near as large but has around 20 columns and is meant to extract two columns from the excel spreadsheet (the first column and the third column). I'm trying to make a form for this database to be as user-friendly as possible and not many people in my office are familiar with the technicalities of Access queries and programming in VBA.
THE SITUATION:
On my form, the user will enter data into TextBoxA, from there they will click a button; this button will trigger a search through the linked excel spreadsheet for the data that was typed into TextBoxA. It will then copy the data from Field1 (which was the typed data) and Field3 and append these selected fields into the first two fields of the table in my Access Database. All of this is being done through a segment of VBA code
Private Sub CmdCloseForm_Click()
If IsNull(Me.TextBoxA) Or Me.TextBoxA = "" Then
MsgBox ("Field is empty, please try again!")
Else
Dim VendorNum As String
SearchingValue = Me.TextBoxA
Dim SQL As String
SQL = "INSERT INTO tbleRecord (Field1,Field2)" & _
"SELECT * " & _
"FROM tbleLinkedExcel " & _
"WHERE Field1 = '" & SearchingValue & "';"
DoCmd.RunSQL SQL
End If
End Sub
So the biggest issue here is that in Field1, and every time I try to run the code,
I receive an error; which I am assuming it is because of the space (unfortunately I cannot give the ACTUAL variable names out as it is confidential)
ERROR MESSAGE
The INSERT INTO statement contains the following unknown field name: 'FIELD 1'. Make sure you have typed the name correctly, and try the operation again.
The thing is, is that this 'FIELD 1' variable/name is not in my code, but in the linked excel spreadsheet (again, I am not able to change ANYTHING on this spreadsheet).
Thanks guys!

MS Access - SetFocus on multiple text boxes to check if data exists via SQL

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.

How do I prevent duplicate entries in my Access database?

I am a first time coder with VBA and I am creating a database for data entry at a Psych Lab I work at. Currently the database is created, but I want to prevent duplicate entries from being put into the database (namely by have a code look for the participant number right after it is entered). I have been trying to fix this code for quite a while and I just recently hit a wall. It displays the correct error message when I enter the participant number, however it says that every number has been entered already (even though they actually haven't). Here is the code:
Private Sub Participant_Number_BeforeUpdate(Cancel As Integer)
Dim Participant_Number As Integer
Dim StLinkCriteria As Integer
If (Not IsNull(DLookup("[Participant_Number]", "Entry Log", "[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
MsgBox "Participant Number has already been entered in the database."
Cancel = True
Me.Participant_Number.Undo
End If
End Sub
Any help is greatly appreciated. I have never used VBA before and I am self-teaching how to code.
I guess your Participant_Number field is a number. You shouldn't enclose the criteria with single-quotes ', these are used with fields of text type. Try changing the criteria field from
"[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
into
"[Participant_Number] = " & Me.Participant_Number.Value))) Then
IF you have not used VBA you may try to do this by opening the table in Design view. This method is easy and a good choice. You may have a look here: https://support.office.com/en-us/article/Prevent-duplicate-values-in-a-field-b5eaace7-6161-4edc-bb90-39d1a1bc5576?ui=en-US&rs=en-US&ad=US&fromAR=1