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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.