访问:Combobox值取决于以前的Combobox

问题描述 投票:0回答:1

所以我有两个组合框,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事件基于我已经完成的测试工作,但无论我选择第一个组合框,第二个组合框都是空的。

vba ms-access combobox access-vba onchange
1个回答
1
投票

组合框AddItem方法将添加项目到组合的ValueList。但我怀疑这是你真正想要的。如果用户在第一个组合中选择“Apple”然后返回并选择“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作为Andre suggested。没有它就不要编写VBA代码。
  3. 考虑将水果名称和选项存储在表格中,并使用查询而不是组合框行源的值列表。然后,当您需要更改可用选项时,请编辑表中的数据,而不是修改VBA代码。
© www.soinside.com 2019 - 2024. All rights reserved.