【问题标题】:Need help adding alphabetical sort to combobox需要帮助将字母排序添加到组合框
【发布时间】:2020-07-08 19:13:41
【问题描述】:

我在 Excel 用户窗体中有一个组合框,我想按字母顺序排序。我不知道如何添加此功能,我将不胜感激。这是我的 VBA:

Private Sub Userform_Initialize()
    ' Sets range for ComboBox list
        Dim rng As Range, r As Range
        Set rng = Sheet1.Range("H2:H65536")

        For Each r In rng
            AddUnique r.value
        Next r
    End Sub


Sub AddUnique(value As Variant)
        Dim i As Integer
        Dim inList As Boolean

        inList = False
        With Me.ComboBox1
            For i = 0 To Me.ComboBox1.ListCount - 1
                If Me.ComboBox1.List(i) = value Then
                    inList = True
                    Exit For
                End If
            Next i

            If Not inList Then
                .AddItem value
            End If
        End With
    End Sub

【问题讨论】:

  • 组合框的值从何而来?如果源是工作表上的某个范围(可能是Sheet1.Range("H2:H65536")),那么只需在将工作表上的值添加到组合框之前对它们进行排序。如果要使用 VBA 进行排序,请在对数据进行排序时录制宏,并使用 Excel 为您生成的 VBA 代码。 (如果您不确定如何手动对工作表进行排序,那么您需要找到一个好的 Excel 教程来帮助您入门。。)
  • 另外,您真的要在组合框中添加 65,000 个项目吗?我想你会有问题。
  • Sort combobox values alphabetically 的可能副本 ...(还有其他几个现有示例。)
  • 我想我应该澄清一下。我无法对组合框值来自的 Excel 表进行排序,因为它是一个分组列表(项目、子项目、工头等)我没有 65,000 个条目,但它是一个动态列表,我的组合框代码从大约 1000 个或更多条目中过滤掉重复项。组合框中只有大约 10 个条目,最好按字母顺序排列。我花了一段时间才找到使这项工作正常工作的代码。作为 VBA 的新手,我不知道如何修改我所拥有的,这就是我问的原因。任何人都可以帮助我修改我到目前为止的代码吗?

标签: excel vba


【解决方案1】:

我的建议是使用Dictionary 来创建仅包含您范围内唯一值的集合,然后在将项目添加到组合框之前对其进行排序。

如果您还没有这样做,请转到“工具”菜单,然后选择“参考”,将参考库添加到您的项目中。向下滚动列表,找到“Microsoft Scripting Runtime”并检查。

然后,循环遍历所有条目是一件简单的事情——只有在项目不存在时才添加它。我从ExcelMastery 中提取了一个排序程序。然后将项目添加到您的组合框。

Option Explicit

Private Sub Userform_Initialize()
    ' Sets range for ComboBox list
    Dim rng As Range, r As Range
    Set rng = Sheet1.Range("H2:H65536")

    '--- create a dictionary of the items that will be in
    '    the combobox
    Dim uniqueEntries As Object
    Set uniqueEntries = New Scripting.Dictionary
    For Each r In rng
        '--- all dictionary keys must be a string
        Dim keyString As String
        If IsNumeric(r) Then
            keyString = CStr(r)
        Else
            keyString = r
        End If
        If Not uniqueEntries.exists(keyString) Then
            uniqueEntries.Add CStr(keyString), r
        End If
    Next r
    Set uniqueEntries = SortDictionaryByKey(uniqueEntries)
    CreateComboboxList uniqueEntries
End Sub

Private Sub CreateComboboxList(ByRef dictList As Scripting.Dictionary)
    Dim key As Variant
    For Each key In dictList.keys
        Debug.Print "Adding " & key
        'Me.combobox1.AddItem key
    Next key
End Sub

'------------------------------------------------------------------
'--- you should put this in a module outside of your userform code
Public Function SortDictionaryByKey(dict As Object, _
                                    Optional sortorder As XlSortOrder = xlAscending) As Object
    '--- from ExcelMastery
    '    https://excelmacromastery.com/vba-dictionary/#Sorting_by_keys
    Dim arrList As Object
    Set arrList = CreateObject("System.Collections.ArrayList")

    ' Put keys in an ArrayList
    Dim key As Variant, coll As New Collection
    For Each key In dict
        arrList.Add key
    Next key

    ' Sort the keys
    arrList.Sort

    ' For descending order, reverse
    If sortorder = xlDescending Then
        arrList.Reverse
    End If

    ' Create new dictionary
    Dim dictNew As Object
    Set dictNew = CreateObject("Scripting.Dictionary")

    ' Read through the sorted keys and add to new dictionary
    For Each key In arrList
        dictNew.Add key, dict(key)
    Next key

    ' Clean up
    Set arrList = Nothing
    Set dict = Nothing

    ' Return the new dictionary
    Set SortDictionaryByKey = dictNew

End Function

【讨论】:

  • 感谢您的帮助和耐心等待!我已经使用 Excel 很长时间了,但现在才使用 VBA 几个星期。我用您提供的代码替换了我的代码。我的组合框现在是空白的。有什么想法我在这里做错了吗?
  • Debug.Print 语句中打印出什么内容?您还可以在For Each r In rng 循环中添加另一个Debug.Print,以查看字典如何/为什么(不)被填充。此代码适用于我使用的测试数据。
猜你喜欢
  • 1970-01-01
  • 2016-09-26
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2015-09-25
  • 1970-01-01
相关资源
最近更新 更多