Reputation: 1396
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".
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
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.
Upvotes: 0
Views: 550
Reputation: 97101
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.
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
Notes:
AfterUpdate
event because its value has been finalized at that point.Option Explicit
as Andre suggested. Don't write VBA code without it.Upvotes: 1