【问题标题】:Is there a way to delete main form data if data in subform is empty?如果子表单中的数据为空,有没有办法删除主表单数据?
【发布时间】:2019-10-24 04:24:21
【问题描述】:

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

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

我该怎么办?

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

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

提前谢谢大家!

【问题讨论】:

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


    【解决方案1】:

    在我看来,如果没有在子表单中输入数据,您希望删除主表单中的记录。我假设子表单中的数据绑定到不同的表,并用于绑定到 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
    

    【讨论】:

    • 您在尝试时“出了什么问题”?不知道如何进一步协助。你收到错误了吗?发生了什么?
    • 对不起,我在第一条评论下方回复,这是代码图片i.stack.imgur.com/jEmXv.jpg 出了点问题,我不太了解你。你猜对了我的结构 - 使 Table1 成为“Porudzbina”(主键“IDPorudžbine”)和子表单 T2 为“PorudzbinaRoba”(“IDPorudžbine”)的主表单
    • 我需要您收到的错误。我知道哪条线路失败了,但我需要知道它失败的原因
    • 感谢@Pants,但我终于找到了解决方案,我花了一整天的时间。 Private Sub Izaði_Click() With [PorudzbinaRoba Query subform].Form If .Recordset.RecordCount = 0 Then DoCmd.RunCommand (acCmdDeleteRecord) DoCmd.Close Else DoCmd.Close End If End With End Sub 感谢您的努力,我使用您的代码明白了一些,你帮了很多忙!!!
    • 我建议编写此解决方案作为您自己问题的答案,然后接受它作为解决方案。这可能会在未来帮助其他人。很高兴我能帮上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多