根据第一个combobox填充第二个combobox

我想根据第一个combobox来填充第二个combobox。
第一个combobox有这些值:John,Marry,Lona,Fred

AB 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中selectJohn时,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 

您的代码现在不起作用,因为您正在searchColumn B (具有数字值的列)以匹配名称。 要修复,使用OFFSETfunction来检查左边的单元格。 例如:

 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 

您遇到的问题是您将rngItems设置为列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 

结束小组