Remove duplicates from array using VBA

前端 未结 8 830
猫巷女王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条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 23:11

    I answered a similar question. Here is the code I used:

    Dim dict As Object
    Dim rowCount As Long
    Dim strVal As String
    
    Set dict = CreateObject("Scripting.Dictionary")
    
    rowCount = Sheet1.Range("A1").CurrentRegion.Rows.Count
    
    'you can change the loop condition to iterate through the array rows instead
    Do While rowCount > 1
      strVal = Sheet1.Cells(rowCount, 1).Value2
    
      If dict.exists(strVal) Then
        Sheet1.Rows(rowCount).EntireRow.Delete
      Else
        'if doing this with an array, then add code in the Else block
        ' to assign values from this row to the array of unique values
        dict.Add strVal, 0
      End If
    
      rowCount = rowCount - 1
    Loop
    
    Set dict = Nothing
    

    If you want to use an array, then loop through the elements with the same conditional (if/else) statements. If the item doesn't exist in the dictionary, then you can add it to the dictionary and add the row values to another array.

    Honestly, I think the most efficient way is to adapt code you'd get from the macro recorder. You can perform the above function in one line:

        Sheet1.UsedRange.RemoveDuplicates Columns:=3, Header:=xlYes
    

提交回复
热议问题