如果子表单中的数据为空,是否可以删除主表单数据?

时间:2019-06-09 13:36:46

标签: forms ms-access subform ms-access-forms

我在MS Access中有一个带有子窗体的窗体。

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

我该怎么办?

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

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

谢谢大家!

1 个答案:

答案 0 :(得分:0)

对我来说,如果子表单中未输入任何数据,则您希望删除主表单中的记录。假设子窗体中的数据绑定到另一个表,并用于绑定到IDOrderNumber的多个记录

我建议使用以下vba代码。我假设您的数据库有些结构,因此请根据需要进行纠正

此代码将出现在您的MainForms Form_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
相关问题