I've created two dependent combo boxes in a form. If you choose a Category
in the first box, it will filter the list of Products
available in the second. I've saved the Category-Product selections to a table called Test
, where Categories get one row each.
What I'd like to do is display the Product in the Product combo box if you select a Category already in Test. For example, if you select Category=Condiments and Product=Ketchup in the form, it's added to Test. Then, the next time you select Category=Condiments in the form, the Products combo box (the box where you type, not the dropdown) will immediately show Ketchup. This only seems to work if I have one row in Test. If I add more rows, ProductComboBox does not change.
Here's how my form is constructed.
In the RowSource for CategoryComboBox, I select everything
Select * From CategoryTable
In the RowSource for ProductComboBox, I filter Products based on the Category selected
Select * From ProductTable Where ProductTable.CategoryID=[forms]![FormTest]![Category]
The form source is Products left joined to Category on CategoryID.
In the On Change event for CategoryComboBox and the On Current event for the form, I requery the ProductComboBox
ProductComboBox.Requery
However, using ProductComboBox.Requery only requeries the options available in the dropdown. It doesn't change the current combo box value after selecting a Category but before selecting a Product. How do I requery data from the table linked to the ControlSource? Is there a better VBA function than Requery
, or do I need to use SQL in a macro?
答案 0 :(得分:1)
在第一个组合框的OnChange事件中,执行以下操作:
Private Sub category_Change()
Dim myID As Long
Me.ProductComboBox.Requery
If Not IsNull(DLookup("ProductID", "tblTest", "CategoryID = " & me.Category)) Then
Me.ProductComboBox = DLookup("ProductID", "tblTest", "CategoryID = " & me.Category)
End If
End Sub
然后更新测试表,如果要更新“default”选项,请输入:
CurrentDb.Execute "UPDATE tblTest SET ProductID = " & Me.ProductComboBox & " WHERE CategoryID = " & Me.Category
这假设“tblTest”已经有每个类别的记录。如果没有,您可以生成一些检查并将该类别插入表中。