我遇到了在MS Access 2003中创建的数据库的问题。我创建了一个包含两个组合框(cboCategory& cboSubCategory),一个文本框(txtDescription)和一个子表单(sbfExistingItems)的表单。 cboSubCategory字段是唯一不需要的字段。我将以下代码添加到txtDescription的GotFocus事件中:
Private Sub txtDescription_GotFocus()
Dim sql As String, child As String, master As String
sql = "SELECT id, description, category, sub_category FROM tblItems"
If IsNull(Me!cboCategory) Or Me!cboCategory = "" Then
' leave recordsource unfiltered
ElseIf IsNull(Me!cboSubCategory) Or Me!cboSubCategory = "" Then
sql = sql & " WHERE [category] = '" & Me!cboCategory & "'"
child = "category"
master = "cboCategory"
Else
sql = sql & " WHERE [category] = '" & Me!cboCategory & "' AND [sub_category] = '" & Me!cboSubCategory & "'"
child = "category;sub_category"
master = "cboCategory;cboSubCategory"
End If
sql = sql & " ORDER BY [description];"
Me!sbfExistingItems.Form.RecordSource = sql
Me!sbfExistingItems.LinkChildFields = ""
Me!sbfExistingItems.LinkMasterFields = ""
Me!sbfExistingItems.LinkChildFields = child
Me!sbfExistingItems.LinkMasterFields = master
End Sub
如果我在没有最后四行的情况下运行它,它可以正常工作(即子窗体的RecordSource得到的设置)。但是,只要txtDescription获得焦点,运行 with 最后四行会导致运行时错误3314(描述不能包含Null值),就像我试图离开主窗体一样必需的txtDescription字段为空。
为什么主窗体允许我编辑子窗体的RecordSource属性,而不是它的LinkChildFields / LinkMasterFields属性?
答案 0 :(得分:1)
因为您在代码中设置了子窗体的记录源,所以无需设置子/主链接。您需要使用代码在表单打开时以及记录更改时设置子表单的记录源,但您不需要链接来执行此操作。