Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 需要帮助添加字母排序到组合框吗_Excel_Vba - Fatal编程技术网

Excel 需要帮助添加字母排序到组合框吗

Excel 需要帮助添加字母排序到组合框吗,excel,vba,Excel,Vba,我有一个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

我有一个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
我的建议是使用字典创建一个仅包含范围内唯一值的集合,然后在将项目添加到组合框之前对其进行排序

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
如果尚未添加参考库,请转到“工具”菜单,然后选择“参考”,将参考库添加到项目中。向下滚动列表,找到Microsoft脚本运行时并进行检查

然后,只需在所有条目之间循环——如果条目不存在,只需添加一个条目。我取消了一个排序程序。然后将项目添加到组合框中

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

组合框的值来自哪里?如果源If是工作表上的一个范围,如Sheet1.RangeH2:H65536,则只需在将值添加到组合框之前对工作表上的值进行排序即可。如果要使用VBA进行排序,请在对数据排序时记录一个宏,并使用Excel为您生成的VBA代码。如果您不确定如何手动在工作表上排序,那么您需要找到一个好的Excel教程来开始。此外,您真的要向组合框中添加65000个项目吗?我想你会有问题的。可能是。。。还有其他几个例子,我想我应该澄清一下。我无法对组合框值来自的excel工作表进行排序,因为它是一个分组列表项目、子项目、foreman等。我没有65000个条目,但它是一个动态列表,我的组合框代码从大约1000个或更多条目中筛选出重复项。组合框中只有大约10个条目,最好按字母顺序排列。我花了一段时间才找到使它正确工作的代码。作为VBA的新手,我不知道如何修改我所拥有的,这就是为什么我问这个问题。有人能帮我修改代码吗?谢谢你的帮助和耐心!我已经使用Excel很长时间了,但现在只使用VBA几个星期了。我用您提供的代码替换了我的代码。我的组合框现在是空的。知道我做错了什么吗?从Debug.Print语句打印出了什么?您还可以在For Each r in rng循环中添加另一个Debug.Print,以查看字典没有填充的方式/原因。这段代码适用于我使用的测试数据。