访问:组合框值取决于前一个组合框

Access: Combobox Values Depend on Previous Combobox

所以我有两个组合框,Combobox1Combobox2。如果用户为 Combobox1 选择 "Apple",我希望 Combobox2 的值为 "Sauce" 和 "Seeds"。

同样,如果用户为 Combobox1 选择 "Blueberry",我希望 Combobox2 的值可以从 "Pie" 和 "Cobbler" 中选择。

我无法弄清楚如何根据第一个选择为第二个组合框设置值。我想应该是这样的...

Private Sub Combobox1_Change()
    If Combobox1= Apple Then
        Combobox2.AddItem "Sauce"
        Combobox2.AddItem "Seeds"
    End If

    If Combobox1= BlueberryThen
        Combobox2.AddItem "Pie"
        Combobox2.AddItem "Cobbler"
    End If
End Sub

根据我所做的测试,onChange 事件正在运行,但无论我为第一个组合框选择什么,第二个组合框都是空的。

组合框 AddItem 方法将向组合框 ValueList 添加一个项目。但我怀疑那是你真正想要的。如果用户在第一个组合中选择 "Apple" 然后返回并选择 "Blueberry",我怀疑你想要第二个组合仅包含 "Blueberry" 选项,而不包含 "Apple""Blueberry"个选择。

通过直接更改 ValueList 属性 来避免这种情况...

Option Compare Database
Option Explicit

Private Sub Combobox1_AfterUpdate()
    Dim strValueList As String

    Select Case Me.Combobox1.Value
    Case "Apple"
        strValueList = "Sauce;Seeds"
    Case "Blueberry"
        strValueList = "Pie;Cobbler"
    Case Else
        MsgBox "What should happen when selection = '" & Me.Combobox1.Value & "'?"
    End Select
    Me.Combobox2.RowSource = strValueList
End Sub

备注:

  1. 使用第一个组合的 AfterUpdate 事件,因为此时它的值已经确定。
  2. Option Explicit 包含为 。没有它就不要写 VBA 代码。
  3. 考虑将您的水果名称和选项存储在 table 中,并使用查询而不是组合框行源的值列表。然后当您需要更改可用选项时,编辑 table 中的数据而不是修改 VBA 代码。