我想根据第一个组合框填充第二个组合框
第一个组合框有这些值:John,Marry,Lona,Fred
A B
1 John 384
2 John 475
3 John 450
4 Marry 616
5 Marry 526
6 Lona 569
7 Lona 234
8 Lona 937
9 Lona 477
10 Fred 286
例如,当我在combobox1中选择John时,在combobox2中应该有这些值:384,475,450
我的代码不起作用:
Private Sub ComboBox1_change()
Set rngItems = Sheet1.Range("B1:B10")
Set oDictionary = CreateObject("Scripting.Dictionary")
With Sheet2.ComboBox2
For Each cel In rngItems
If ComboBox1.Value = cel.Value Then
oDictionary.Add cel.Value, 0
.AddItem cel.Value
End If
Next cel
End With
End Sub
答案 0 :(得分:2)
您的代码无法正常工作,因为您正在搜索Column B
,即带有数值的列,以匹配名称。要解决此问题,请使用OFFSET
功能检查左侧的单元格。例如:
Private Sub ComboBox1_change()
Set rngItems = Sheet1.Range("B1:B10")
Set oDictionary = CreateObject("Scripting.Dictionary")
With Sheet2.ComboBox2
For Each cel In rngItems
If ComboBox1.Value = cel.Offset(,-1).Value Then
oDictionary.Add cel.Value, 0
.AddItem cel.Value
End If
Next cel
End With
End Sub
答案 1 :(得分:1)
您遇到的问题是您要将rngItem设置为B列。您要将其设置为A列,然后从B列中获取值。试试这个:
Set rngItems = Sheet1.Range("A1:A10")
Set oDictionary = CreateObject("Scripting.Dictionary")
With Sheet2.ComboBox2
For Each cel In rngItems
If ComboBox1.Value = cel.Value Then
oDictionary.Add Cells(cel.row, cel.column + 1).Value, 0
.AddItem Cells(cel.row, cel.column + 1).Value
End If
Next cel
End With
End Sub