Delete record if no records exist in sub-form

SteveL13 used Ask the Experts™
I have a form with a sub-form.  If the user has not entered any records in the sub-form and clicks the [Close Form], (a customer command button on the main form), I want the main record to be deleted without warning.

How can I do this?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead


Private Sub  btnClose_Click()
   ID = Me.txtID.Value 'or something you can refer to present the unique main record
   If Me.yourSubform.Form.RecordsetClone.RecordCount = 0 Then
      CurrentDB.execute "Delete from yourMaintable where id = " & ID
  End If
End Sub
Most Valuable Expert 2015
Distinguished Expert 2018
You can just delete the record:
Private Sub Form_Unload(Cancel As Integer)

    If Me!NameOfSubformControl.Form.RecordsetClone.RecordCount = 0 Then
        DoCmd.RunCommand acCmdDeleteRecord
    End If

End Sub

Also, to prevent the dialogue box:

Private Sub Form_BeforeDelConfirm(Cancel As Integer, Response As Integer)

    Response = acDataErrContinue

End Sub

Open in new window

Jeffrey CoachmanMIS Liason
Most Valuable Expert 2012

Note that things like this go against basic referential integrity rules, and may be hard to control when your design becomes more complex.

In a standard situation it is fairly common for a Parent record to be created and not have any Child records.
(The problem arises if you have child records with no parent (orphaned records))
For example, A person will become a Patient and not necessarily make an appointment for a "Visit" for a few weeks.
You can become a student at a school and not register for classes until the next semester.

Your users may wonder why a customer they created yesterday, not showing up today?

Is this new "rule" to be universal with all Parent/Child relationships?
If not, then it will be confusing to users as to when a parent record will persist, and when it will "disappear"

As usual, an explanation of why this is needed is always helpful.
Again, deleting Parent records automatically (and without notice) is something that is not commonly done.



I do understand that this is highly unusual.  But in this case, if the user starts a record on the main form and does nothing with the child form, he/she wants the main record to be deleted.

Strange but true.

Jeffrey CoachmanMIS Liason
Most Valuable Expert 2012

Ok, then what the experts above posted, ...should get you on your way...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial