使用唯一值填充组合框而无需使用scripting.dictionnary

时间:2017-01-03 15:52:46

标签: excel-vba combobox vba excel

到目前为止,我找到了一种方法来填充我的组合框,但它在尝试创建对象时不起作用(错误429)。 这是我找到的代码:

Dim v, e
c = 2
ld = 8
lf = 128
With Sheets("2017-Sem1").Range(Cells(ld, c), Cells(lf, c))
    v = .Value
End With
With CreateObject("scripting.dictionnary")
    .comparemode = 1
    For Each e In v
        If Not .exists(e) Then .Add e, Nothing
    Next
    If .Count Then Me.ComboBox1.List = Application.Transpose(.keys)
End With
End Sub

首先,我并不完全清楚代码的作用,如果你能引起我的注意,我将不胜感激。 其次,似乎" scripting.dictionnary"在我的电脑上不存在: 我试过了

dim dict as scripting.Dictionnary 

并立即返回编译错误。

所以,据我所知到目前为止,我将无法使用它(缺少DLL,我不能在我的工作中进入文件夹)。 有没有人有我可以使用的替代解决方案?

谢谢你, PEagle

1 个答案:

答案 0 :(得分:1)

您可以稍微改变一下 - 您不一定需要Dictionary(或Collection)。只需使用Combobox.List对象即可。此VBA代码采用范围A1:A10中的值,只有在它是唯一的时候才会添加到您的组合框中。该代码旨在用于 UserForm Module

Sub Userform_Initialize()
    Dim rng As Range, r As Range
    Set rng = Sheet1.Range("A1:A10")

    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

我测试了代码,它对我很有用。如果您有任何问题,请告诉我

相关问题