Is there a way to delete main form data if data in subform is empty? - forms

I have a form in MS Access that has a subform.
My problem is that if the user starts filling the main form with date, customer, IDOrderNumber etc. and suddenly wants to leave the form without entering data in the subform, when he tries to find that form with the same IDOrderNumber, he can't. But when he enters the same IDOrderNumber he can't because it's the primary key and can't allow duplicate values.
What should I do?
I tried to add a search field for IDOrderNumber but it doesn't work - it shows empty Master and Child form/subform. Also I have an Order list Form and I can't access a form that has no subform data entered..
I need a solution because it is a big problem for my customer/user of database.
Thanks all in advance!

The way it sounds to me, is that you want the record in the main form to be deleted if no data is entered in the subform. Ill assume the data in the subform is bound to a different table, and used for multiple records tied to IDOrderNumber
I would suggestion using the below vba code. I'm assuming some of your database's structure, so correct me as needed
This code will go in your MainForms Form_Close() Event
Private Sub Form_Close()
Dim recordexists as Integer
Dim db as Database
Dim rs as Recordset
Dim strSQL as String
strSQL = "SELECT * FROM YourSecondaryTable T2 WHERE T2.IDOrderNumber =" & Me.IDOrderNumberField.Value
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL)
'This recordset is checking to see if a value in the secondary table exists with the OrderNumber that exists in the main table.
With rs
If Not .BOF And Not .EOF Then
.MoveFirst
While (Not .EOF)
'If the code gets to this point, then a record exists in your subform.
'So we set the value to 1
recordexists = 1
Wend
End If
.Close
End With
'If the above recordset didnt find anything, the the recordexists value would never be set.
'Therefore you want to delete the parent record. So we delete it
If recordexists = 0 Then
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE TOP 1 FROM YourMainTable T1 WHERE T1.IDOrderNumber = " & Me.IDOrderNumberField.Value
DoCmd.SetWarnings True
End IF
Set rs = Nothing
Set db = Nothing
End Sub

Related

How do I search forms in Access using values from another table that is being referenced?

The management staff in my department has been asked to record any and all errors committed by our team. I created a database to store them and a simple form for the management team to use to record each error. Several fields are referencing other tables such as Staff, issue category, root cause, etc...
We need to be able to search the forms for specific records to either update or review, and I have found the best way for us to search is by filtering the forms based on the individual who committed the error. Here is the code that I am using for the search button:
Private Sub SearchRecord_Click()
Dim Search As String
Search = InputBox("Please enter who committed the error", "Name", ErrorMadeBy)
If Search = "" Then Exit Sub
Me.Filter = "ErrorMadeBy = """" & Search & """
Me.FilterOn = True
End Sub
The filter works great, but instead of filling out the name, you have to use the ID number in the Staff table when filling out the Input Box. I'd like to be able to input the name (or part of the name) instead of having to have everyone memorize the ID numbers from the staff table.
What I do in these cases?
Fire up the query builder - left join in those extra tables (with the text parts in place of the id).
So be it a part number, quote number for a project etc? Just left join in those tables in the query builder and save that query.
Now, your search box and code can be somthing like:
dim rst as DAO.RecordSet
strSQL = "Select * from MyCoolQuery where PartName like '" & txtPartName & "*'"
set rst = currentdb.OpenRecordSet(strSQL)
if rst.EOF = false then
me.RecordSet.FindFirst "PartID = " & rst!PartID
end if
In fact, you can even often left join in those extra tables right into the current form, and even use ctrl-f to search if the said text boxes are place on the given form. However, I tend to separate out the search process from the actual form. So I might build a search form, say like this:
So in above, they can search say by a Hotel name, or project name or whatever. Becuase the one query has the text parts, then they can be searched. But I put the query results into a grid and each row of course has the PK ID, and thus a search could result in 10 matches, they are now free to click on any row - and i jump to the form to display the one records.
eg: the row click button does this:
docmd.OpenForm "frmTourBooking",,,"ID = " & me!ID
So, this makes for a great work flow. Users search, see, pick and then jump to the form with the one record, and then close and return back to search form - and often it has the several "hits" from that search that you want to work on anyway.

Deleting/Adding records on a subform that has a similar record source of the main form

I am trying to make a subform that works similarly to a splitform.
I would use splitform but, as far as I could tell, I can't filter only the results of the datasheet portion of the split form, and not the results of the rest.
See here...
The subformPartDetail only returns records where the OrderID is equal to the mainform's OrderID. There is no filter in the mainform so it returns all partDetail Records regardless of the OrderID. In this particular instance, the main form has 21 records to cycle where as the subform only has four.
An issue occured when I use the subform for adding or deleting records. When I try to use the main form to cycle through the records, the added ones were skipped and the deleted ones threw an error telling me that the record I was attempting to go to has been deleted.
I corrected it like this by putting these on the subform events...
Private Sub Form_AfterInsert()
Dim frm As Form
Dim rst As Recordset
Set frm = Forms!PartDetails
Set rst = frm.Recordset
rst.Requery
End Sub
Private Sub Form_Delete(Cancel As Integer)
Dim frm As Form
Dim rst As Recordset
Set frm = Forms!PartDetails
Set rst = frm.Recordset
rst.Requery
End Sub
But say I try to delete the record the mainform is displaying from the subform. That code does not work and will not requery. It throws an error when I cycle away from and then back to that record.
How can I fix this?
I know I can move the record from the deleted one before it deletes by using
rst.move
I don't know where to began for testing whether the record that is being deleted is the same one that the main form is displaying.
Maybe I'm not understanding the situation correctly, but there shouldn't be any need for VBA to achieve this. If the subform is using the Link Master Fields and the Link Child Fields with your subform, those IDs would work automatically. And if you have a relationship set up between the two tables, if you delete the Order record (and have Enforce Referential Integrity: Cascade Delete) selected, it should clear out the line items automatically to avoid orphan records.

How to add a multiple values field to an MS Access form

I have a database which records and tracks the training records for each employee within our group of companies.
One of the forms on the database is 'add training record' and currently this is done per person ID, adding the course id, date, certificate, etc. What I would love to do is be able to add multiple person IDs, as a number of people can attend the same course/ date, so I have to add the course details in many times, which is very time consuming and annoying.
You're going to need extensive VBA behind the scenes to do this, as well as a couple of controls to make your life easier (multi-select combo or list boxes). You could do it in a text box if you want, using the semi-colon between User IDs.
Since the text box is easier, let's look at that. What you would do is have something like this behind the Submit button:
Dim db as Database
Dim rec as Recordset
Dim str as String
Set db = CurrentDB
Set rec = db.OpenRecordSet("SELECT * FROM tblMyTable")
'Throw the User IDs into an array
Dim var As Variant
Dim i As Long
str = me.txtUserIDs
var = Split(str, ";")
'For every User ID, add a new record to the database
For i = 0 To UBound(var)
rec.AddNew
rec("UserID") = var(i)
rec("CourseID") = Me.txtCourseID
rec("CourseDate") = Me.txtCourseDate
'ETC... adding fields as needed
rec.Update
Next i
This is completely off-the-cuff and (of course) requires you to change the appropriate variable names, but it should give you a solid outline for how to solve the problem.

Trying to design form to query and edit records Access

I'm trying to make an Access database where we can scan in a list of bar-codes, batch edit information for them, then save all the records. Later, they will need to be scanned again to batch edit more information such as shipping and order numbers.
Does anyone have suggestions on how to best design this? To start with, I've (1) made separate tables for "orders" and "parts" and (2) created a form of text boxes and a button attempting to apply this info to a part subform where records are created via the bar-code scanner. I'm a rather new Access designer. Thanks!
The questions are:
I'm not sure how to query these records via the bar code (Part_ID field) to apply order information to them later.
I can't currently update all new part records at once through my form.
Here's a little guide on how to do it. Let me know if you have any questions.
Dim db As DAO.Database
Dim Rs As DAO.Recordset
'Here is an example of a vba qarry in access. tblOrdersWhere is obviously your table.
'orderNum is a column name in your table pref a primary key
'txtOrderNum.Value is the value of a text box
'If you want just a simple select * from table you can put after db.OpenRecordset("tblOrders")
set rs = db.OpenRecordset("Select * from tblOrders Where orderNum like '*" & txtOrderNum.Value & "*';", dbOpenDynaset)
'This is how you update records in Access
'If you want to update it's Rs.Edit instead of Rs.AddNew
Rs.AddNew
Rs("OrderItem").Value = txtGroupName.Value
Rs("OrderTime").Value = txtGroupNum.Value
rs.Update

Access 2003 Need to create a user interface where user can select from field list and return distinct values

I'm still working with the same database in which the table name stays the same but the field names will be different for each use. I'd like to create an option on the main form where the user clicks a command button to display a list of fields in the table (named'Scrubbed'), then selects a field from the list, and immediately a window opens up displaying the distinct field values. Can this be done?
You can do a lot with VBA, including creating a query on the fly. Comboboxes and listboxes have a RowSource option Field List, which will list the fields in your table.
Edit
Here is your code with a few changes:
Private Sub Command206_Click()
Dim strSQL As String
Dim strScrubbedValue As String
''I suspect this is running in the form, so Me
strScrubbedValue = Me.ComboListScrubbedFields
''Where the table is called Scrubbed
strSQL = "SELECT DISTINCT " & strScrubbedValue & " FROM Scrubbed"
''No need to execute, it is just a row source
''DoCmd.RunSQL strSQL
Me.Combo213.RowSource = strSQL
End Sub
I suggest you name your controls with meaningful names.