Combobox以升序显示项目

时间:2017-04-25 13:24:50

标签: excel-vba vba excel

在belwo编码的帮助下,我能够从组合框中删除重复的项目,但它不能按升序反映项目。我想按升序反映组合框中的所有项目。 请协助。

ComboBox37.Clear
With CreateObject("Scripting.Dictionary")
    For Each rCell In wksSource.Range("M6", wksSource.Cells(Rows.Count, "M").End(xlUp))
            If Not .exists(rCell.Value) Then
                .Add rCell.Value, Nothing
            End If
    Next rCell
    ComboBox37.List = .keys
End With

2 个答案:

答案 0 :(得分:0)

你所拥有的是一个良好的开端,你只需要在他们全部加载后立即对它们进行排序:

ComboBox37.Clear
With CreateObject("Scripting.Dictionary")
    For Each rCell In wksSource.Range("M6", wksSource.Cells(Rows.Count, "M").End(xlUp))
            If Not .exists(rCell.Value) Then
                .Add rCell.Value, Nothing
            End If
    Next rCell
    ComboBox37.List = .keys
End With

With ComboBox37
    For a = 0 To .ListCount - 1
        For b = a To .ListCount - 1
            If .List(b) < .List(a) Then
                c = .List(a)
                .List(a) = .List(b)
                .List(b) = c
            End If
        Next
    Next
End With

答案 1 :(得分:0)

ArrayList是此类案例的另一个有用的数据结构,它支持Contains方法(类似于Dictionary.Exists方法)和Sort方法。这将非常有用,尤其是如果您不想操纵(排序)工作表数据本身:

Dim list As Object
Set list = CreateObject("System.Collections.ArrayList")
Set rng = wksSource.Range("M6", wksSource.Cells(Rows.Count, "M").End(xlUp))
ComboBox37.Clear
For Each rCell In rng.Cells
    If Not list.Contains(rCell.Value) Then list.Add (rCell.Value)
Next rCell
Dim v
'Sort the ArrayList object:
list.Sort
ComboBox37.list = list.ToArray()
Set list = Nothing