【问题标题】:Excel VBA - Populate a Combobox given selection of another ComboboxExcel VBA - 在选择另一个组合框的情况下填充组合框
【发布时间】:2015-03-28 18:00:10
【问题描述】:

在选择第一个组合框的情况下,我正在尝试填充第二个组合框。第一个组合框是工作表上所有列的名称。第二个组合框应显示该列中除重复项之外的所有值。下面的代码填充combobox1。我正在努力解决如何在给定不同列名的情况下从列中取出数据。感谢您的帮助。

Dim myArray As Variant

lastcol = Sheets(4).Range("A1").End(xlToRight).Column
With Sheets(4)
Set SourceRng = .Range(.Cells(1, 1), .Cells(1, lastcol))
End With
myArray = WorksheetFunction.Transpose(SourceRng)

With Me.ComboBox1
.List = myArray
End With

【问题讨论】:

    标签: excel combobox filter vba


    【解决方案1】:

    您可以尝试获取combobox1listindex。请记住,ListIndex 是基于 0 的,而 Excel 行和列不是:

    Private Sub ComboBox1_AfterUpdate()
    
    Dim selectedCol as Variant
    selectedCol = Me.ComboBox1.ListIndex + 1
    
    Set SourceRng = ws.Range(Cells(2, selectedCol), Cells(4, selectedCol))
    
    Me.ComboBox2.List = WorksheetFunction.Transpose(SourceRng)
    
    End Sub
    

    去除重复值和垃圾:Set SourceRng = ws.Range(Cells(varRow, Me.ComboBox1.ListIndex + 1), Cells(varRow2, Me.ComboBox1.ListIndex + 1)).RemoveDuplicates Columns:= selectedCol, Header:=xlNo

    这是删除重复项的解决方法。使用 Range 类的 RemoveDuplicates 函数将删除您的行,我假设您不希望这样:

    
    Private Sub ComboBox1_AfterUpdate()
    
        Dim colSelect As Integer
        colSelect = Me.ComboBox1.ListIndex + 1
    
        Set SourceRng = ws.Range(Cells(2, colSelect), Cells(5, colSelect))
    
        SourceRng.Sort SourceRng, xlDescending
    
        Dim c
        For Each c In SourceRng.Cells
            If c.Value  c.Offset(-1, 0).Value Then
                Me.ComboBox2.AddItem c.Value
            End If
        Next
    
        'You would take out the array and assigning it to the Combobox2.List
    
    End Sub
    

    【讨论】:

    • 这工作得很好,通过一些额外的代码让它自动调整到长度。现在只是为了摆脱重复和空白。
    • Range(Cells(rowHere,colHere),Cells(rowHere,colHere)).RemoveDuplicates
    • 抱歉,这个有点新。如何将其合并到其他代码中?到目前为止,我无法让它删除任何东西。
    • 我将其添加到我的答案中。它应该与设置 SourceRng 变量一起使用
    • 这就是我的想法,但是当我将其添加到末尾时,它说类型不匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2011-11-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多