【问题标题】:Filling the second combo box based on the first combo box根据第一个组合框填充第二个组合框
【发布时间】:2015-02-20 04:18:29
【问题描述】:

我想根据第一个组合框填充第二个组合框。
第一个组合框具有以下值: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

【问题讨论】:

    标签: vba excel combobox


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      结束子

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多