所以我有两个组合框,Combobox1
和Combobox2
。如果用户为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”,我怀疑你希望第二个组合仅包含“蓝莓”选项,而不是“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
笔记:
AfterUpdate
事件,因为它的值已在该点完成。Option Explicit
作为Andre suggested。没有它就不要编写VBA代码。