访问:组合框值取决于以前的组合框 [英] Access: Combobox Values Depend on Previous Combobox

查看:60
本文介绍了访问:组合框值取决于以前的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个组合框, Combobox1 Combobox2 .如果用户为 Combobox1 选择苹果",则我希望 Combobox2 的值为调味"和种子".

So I have two comboboxes, Combobox1 and Combobox2. If the user chooses "Apple" for Combobox1, I want the values for Combobox2 to be "Sauce" and "Seeds".

同样,如果用户为Combobox1选择了蓝莓",我希望Combobox2的值可以是"Pie"和"Cobbler".

Likewise, if a user picks "Blueberry" for Combobox1, i'd like Combobox2 values to choose from be "Pie" and "Cobbler".

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

I'm having touble figuring out how to make the values for the second combobox based on the first choice. I think it would be something like this...

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事件基于我已经完成的测试而工作,但是无论我为第一个组合框选择什么,第二个组合框都是空的.

The onChange event is working based on test i've done, but no matter what I pick for the first combobox, the second combobox is empty.

推荐答案

组合框 AddItem 方法会将一个项目添加到组合的 ValueList 中.但我怀疑那是您真正想要的.如果用户在第一个组合中选择了"Apple" ,然后返回并选择了蓝莓" ,则我怀疑您希望第二个组合仅包含"蓝莓" 选项,而不是同时选择苹果" 蓝莓" 选项.

The combobox AddItem method will add an item to the combo's ValueList. But I doubt that is what you really want. If the user selected "Apple" in the first combo and then went back and selected "Blueberry", I suspect you want the second combo to contain only the "Blueberry" choices, not both the "Apple" and "Blueberry" choices.

避免直接更改 ValueList 属性...

Avoid that by altering the ValueList property directly ...

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. 请考虑将您的水果名称和选项存储在表中,并使用查询而不是组合框行源的值列表.然后,当您需要更改可用选项时,请编辑表中的数据,而不用修改VBA代码.
  1. Use the first combo's AfterUpdate event because its value has been finalized at that point.
  2. Include Option Explicit as Andre suggested. Don't write VBA code without it.
  3. Consider storing your fruit names and options in a table and using queries instead of value lists for the combobox row sources. Then when you need to change the available choices, edit the data in the table instead of revising VBA code.

这篇关于访问:组合框值取决于以前的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆