首页 > 解决方案 > 如果子表单中的数据为空,有没有办法删除主表单数据?

问题描述

我在 MS Access 中有一个包含子表单的表单。

date我的问题是,如果用户开始用,customer等填充主表单IDOrderNumber并且突然想要离开表单而不在子表单中输入数据,当他尝试使用相同的 找到该表单时IDOrderNumber,他不能。但是当他输入相同的内容时,IDOrderNumber他不能,因为它是主键并且不允许重复值。

我应该怎么办?

我试图添加一个搜索字段,IDOrderNumber但它不起作用 - 它显示空的主表单和子表单/子表单。另外我有一个订单列表表单,我无法访问没有输入子表单数据的表单..

我需要一个解决方案,因为这对我的数据库客户/用户来说是一个大问题。

提前谢谢大家!

标签: formsms-accesssubformms-access-forms

解决方案


在我看来,如果没有在子表单中输入数据,您希望删除主表单中的记录。我假设子表单中的数据绑定到不同的表,并用于绑定到 IDOrderNumber 的多个记录

我建议使用下面的 vba 代码。我假设你的一些数据库结构,所以根据需要更正我

此代码将进入您的 MainFormsForm_Close()事件

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

推荐阅读