基于第一个组合框填充第二个组合框

Filling the second combo box based on the first combo box

我想在第一个组合框的基础上填充第二个组合框。
第一个组合框具有这些值: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

您当前的代码无法正常工作,因为您正在搜索 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

您遇到的问题是您将 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

结束子