Remove duplicates from array using VBA

前端 未结 8 831
猫巷女王i
猫巷女王i 2020-11-27 22:12

Assume I have a block of data in Excel 2010, 100 rows by 3 columns.

Column C contains some duplicates, say it starts off as

1, 1, 1, 2, 3, 4,

8条回答
  •  Happy的楠姐
    2020-11-27 23:05

    Dictionaries have a max of 255 items, so if you have more values you need to use a Collection. Unfortunately, the Collection object does not have a .Contains(a) or .Exists(a) method, but this function handles (fakes it) it nicely by using the Error numbers:

    CORRECTION: Dictionaries do not have such a limit (thanks Zairja). I may have been using an Integer to iterate through my Dictionary. In any event, this function allows you to check Collections for item existence, so I'll leave it here if it's useful to anyone:

    CollContainsItem(col As Collection, val As Variant) As Boolean
    
    Dim itm As Variant
    On Error Resume Next
    
        itm = col.Item(val)
        CollContainsItem = Not (Err.Number = 5 Or Err.Number = 9)
    
    On Error GoTo 0
    
    End Function
    

    So if you do need a Collection, you could likely just replace

    dict.Exists(strVal)
    

    with

    CollContainsItem(coll, strVal)
    

    and replace

    Set dict = CreateObject("Scripting.Dictionary")
    

    with

    Set coll = CreateObject("Scripting.Collection")
    

    And use the rest of Zairja's code. (I didn't actually try it but it should be close)

提交回复
热议问题