Excel VBA - 在给定选择另一个组合框的情况下填充组合框

Excel VBA - Populate a Combobox given selection of another Combobox

在选择第一个组合框的情况下,我正在尝试填充第二个组合框。第一个组合框是 sheet 上所有列的名称。第二个组合框应显示该列中除重复值之外的所有值。下面的代码填充 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

您可以尝试获取 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

这是删除重复项的解决方法。使用范围 class 的 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