A little Access VBA help? Validating against duplication of a non key field? - ms-access

I am adding a part name to the database using a form, What code do I put behind the Add part button to validate against duplicate part names? (part number is the primary key) I think I need another recordset to search and compare the table but i'm a bit lost, any help would be great.
Private Sub btn_add_Click()
rs_parts.AddNew
With rs_parts
!partrno = lbl_partno.Caption
!Name = txt_name
rs_parts.update
end with

I've discussed my approach to this before, and given an example form for adding a new record.
I use an unbound form to collect the information needed to create the new record, and have it check for duplicates, and present a list of them to the user so the user can decide what to do.
In this case, it sounds like a unique index is in order, so you won't really need to worry about close matches. I would probably still use an unbound form to capture the new value and run the check before even attempting to add it. In that case, I'd just notify the user that it's a dupe.

Should you add a unique index to the part name field?
If you want, you can create a query on your part table with one column for the name and a parameter for the criteria they've entered in txt_name. Then pass the value they entered as a parameter to the query and see if you get any results.

Related

How to edit an existing record and not create a new one when using subforms in Access?

I have an access database that holds medical information. It holds quite a bit of information so i have grouped like fields together into individual tables and linked them using a common primary key. I have created a tab style form with subforms on each tab.
Some of these subforms contain fields from only one table, however there are a few subforms where i have included fields from more than one table.
For example, i have a table that holds blood transfusion data and a table that holds patient characteristics. Some Fields from the blood transfusion table and patient characteristics table are in the same subform, but I also have fields from both these tables in other subforms.
When i try to insert data into the sub-forms with fields from multiple tables i get the following errors..
update or cancelupdate without addnew or edit
and
The changes you requested to the table were not successful because
they would create duplicate values in the index, primary key or
relationship. Change the data in the field or fields that contain
duplicate data, remove the index, or redefine the index to permit
duplicate entries and try again.
From researching the problem i gather this is because access is trying to create a new record for both tables, but if a record has already been created with that primary key (from inserting data into a previous subform) it won't edit the existing record.
Does anyone know how to get access to edit the existing record in this instance instead of trying to add a new record? I have basic skills in VBA but this is a bit past my level of experience.
Any suggestions would be greatly appreciated.
I used have a whole long response about split forms instead but I was having a horrible time getting it to work. So here is my new and improved answer for using subforms.
Here is a link with sub form info if you want to brush up for your purposes https://support.office.com/en-us/article/Create-a-form-that-contains-a-subform-a-one-to-many-form-ddf3822f-8aba-49cb-831a-1e74d6f5f06b
Step 1
Make sure your main form is bound to the right table.
For my purposes I used a single combo box on my main form to search with. Make sure all the field parameters on your combo box are correct. This includes making sure the Row Source is correct and that you DO NOT have a control source entered.
Step 2
Don't press enter after making a selection in the combo box. To prevent people from hitting enter I created a dummy button at the bottom that says "Save and Refresh" but all it does it create a message window that pops up with "Save Successful". I find hitting enter creates the first error you keep getting. I'm not sure how to address this in a more sophisticated way yet.
Anything else that comes up I will add later.

DCount for duplicates not allowing user to keep old field if they accidentally edited it

In the BeforeUpdate event on my field, I have a dcount set up to disallow duplicates in the field SurveyID. This works great, except in the event that, in a past record, the user starts editing their SurveyID by accident and tries to cancel (accidentally selects the SurveyID field, starts typing, then erases it and enters the SurveyID). It reads that SurveyID as a duplicate (even though it's not really) and won't allow them to keep the ID. I've already done a half workaround by having the SurveyID reset after this, so if they're in the above scenario they can at least retain their ID. What I really want to know if there's a way with my code to prevent this from happening. The SurveyId is NOT the primary key, as there are two different ID codes they could have used. Maybe an extra piece of logic saying that if the primary key in that record in the form matches with the primary key of the "duplicate" (aka itself) then it doesn't get processed at a duplicate?
Here is my current code
Private Sub SurveyID_BeforeUpdate(Cancel As Integer)
'checks for duplicates'
If DCount("SurveyID", "test", "SurveyID=" & Nz(Me.SurveyID, 0)) > 0 Then
Beep
MsgBox "The Survey ID number you have entered is a duplicate. Please double check that the number you entered is correct. If it is correct, please X."
Me.SurveyID.Undo
Cancel = True
End If
End Sub
Have you tried setting SurveyID to be indexed as Yes (No Duplicates)? As long as Required is also set to No it should not allow you to enter a duplicate value but you can also leave it blank if you wish.
You should still be able to trap the error in the form's On Error event so you can display a friendly message.
This is exactly why having a bound form is a bad idea. Never, ever bind a form to a table. Undoing an entry is wonky at best, and the way a bound form works is that as soon as you change fields, the record is written to the table. Yes, there is an Undo command but it's not reliable.
Unbind the table from the form, and write code that either updates a record (if it already exists) or writes a new record when you press a "Submit" button. It's a lot more coding and requires a better understanding of Access, but it's the proper way to do this.

remove value in subform

In one of my access forms I use a continuous sub form with just one field per line that creates an entry in a junction table.
While creating and changing entries in the junction form works fine, I have problems removing those entries. When I clear a line in the sub form, the entry should be deleted. Instead I get an alert message "Null value in index or primary key not possible".
I think I need some vb-programming to solve that problem, right? What would be a propper approach for that?
(I don't use MS-Access regularly so maybe I misused some technical terms. Please be kind.)
[edit]
I now use a delete button instead. I leave the topic open for the moment just in case somebody wants to add an answer.
Since you are (assumingly) using bound forms, every entry on your form is directly written into the table. Since your primary key is not allowed to be Null, it immediatly presents you with the alert.
There are different ways to solve this problem, depending on your goals.
If you want to allow empty entry's in the field that's momentarily your primary key, you should remove the key in the design view of your table.
If you want to disallow the empty entries, but want a custom error message or the message to appear after clicking a save button, you should change to an unbound form.

Microsoft Access Form To Query for Multi Value Field

I am trying to write an Microsoft Access query from a form with a multi value field being the criteria. The field I am trying to use is called Population and the field is represented in my database as a List Box that allows multiple values and it is in the Building table. The values it allows are the following:
"Singles";"Familes";"Families with Children";"Youth/Young Adults";"Veterans";
The form that I am creating is called HousingSearch.
I am trying to create a form which uses this field, so someone could use the list box and check off the values they want and click on the button which would open a query. I know having done this with single value fields the criteria in the query looks something like
[forms]![HousingSearch]![Building]![Population]
but if you try the same thing for a multi value field nothing is returned for the query. Any help would be appreciated.
From the information you have provided it seems that the phrase [Forms]![HousingSearch]![Building]![Population] are combining a request that starts with a form and then jumps to a table.
You are asking access to find data in a form but the information you're most likely trying to access is in a table. I don't quite understand what you're end result is but I think that you most likely want to refer to your information this way [Building]![Population]. Referring to your data this way makes access look at the table of [Building] and then into the field of [Population].
It's been a while since you posted, if you haven't cleared things up already I hope this helps.

How to look up values from a table in Access

I have an Access database that is used to store basic info in a table such as first and last name. How would I go about adding the functionality to lookup by last name?
Is there a way to type in the last name and then hit like F12 or something like this? Can someone please point me in the right direction or provide me a link?
SELECT tblPatient.LName AS [Last], tblPatient.FName AS [First]
FROM tblPatient
WHERE (((tblPatient.LName)=[Enter Last Name]));
How do I tie this into my form now?
I'd suggest you create a form, with a textbox 'search' at the top, then either a listbox or subform below to display results.
The listbox record source would be:
SELECT tblPatient.LName, tblPatient.FName
FROM tblPatient
WHERE tblPatient.LName LIKE Forms!myForm!search & '*';
You can either add a Search button, which requeries the listbox, or do the requery via the Change event of the search textbox. The later may be slow if you have a large number of records; if that's the case, you could check that at least 3 (?) characters have been entered before calling the requery.
You just need to create a query in which you put =[?] as the "last name" value.
When you open that view, you'll be asked to type in a lookup value for that field.
Not sure if this is what you are trying to archieve, though...
This is probably a bit overkill for what you want to do, but I assume that you want to perform a search by last name. You should be able to glean the information you need from this article:
Build a search criteria form
http://www.everythingaccess.com/tutorials.asp?ID=Build-a-search-criteria-form
You can create queries in Access if the user you're targeting with the searchability has Access themselves.
From the main Access UI (assuming Access 2007), go to the Create tab and then select the "Query Wizard." Here is an article on the subject.
Otherwise you can create a program and connect to the MDB/ACCDB file running the query programmatically.
Seeing you wish to look up a name and populate the form based on the name selected, I suggest you need a combobox. There is even a wizard for doing exactly what you want. To start, you will need a form bound to a table or query, that is a form with a Record Source.
Add a combobox to your form
Select :
Find a record on my form based on the value I select in my combobox
Select the ID (primary key), Last and First name fields.
Access will display an example, suggesting that you hide the Key (id) column. Accept this.
Choose a name and finish.
There are a few other small things that could be done for neatness, but you will end up with a form that find the record you want. In addition, the combo will autocomplete if you type in a few letter.
If this is an mde, which your subsequent post seems to suggest it is, there is little you can do wuth out the original file. However, you could try opening the database while keeping the shift key held down and see if that allows you to edit. If you cannot get the original and the shift does not work, you could try rescuing the data, if it, too, is stored in this file.