VBA,从数组中删除重复

有人可以请给我一些指导,如何解决以下问题:

假设我在Excel 2010中有一个数据块,100行×3列。

C列包含了一些重复项,比如它的起点为1,1,1 2,3,4,5,…..,97,98

使用VBA,我想根据列C删除重复的行,以便我留下1,2,3,…..,97,98,即只有98行和3列。

我知道有一个button,我可以在Excel 2010中单击来做到这一点,但我想在VBA中做到这一点(因为我已经试过这个,出于某种原因,随后与我的其他代码inteferes,并给出不正确的结果)。

此外,我想在数组中做到这一点,然后将结果粘贴到工作表上,而不是像Application.Worksheetfunction.countif这样的方法(…..

所以像这样:

Dim myarray() as Variant myarray=cells(1,1).Currentregion.value Dim a as Long For a=1 to Ubound(myarray,1) 'something here to Next a 

我回答了一个类似的问题 。 这是我使用的代码:

 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 / else)遍历所有元素。 如果项目不存在于字典中,则可以将其添加到字典中,并将行值添加到另一个数组中。

老实说,我认为最有效的方法是调整你从macroslogging器得到的代码。 您可以在一行中执行上述function:

  Sheet1.UsedRange.RemoveDuplicates Columns:=3, Header:=xlYes 
 Function eliminateDuplicate(poArr As Variant) As Variant Dim poArrNoDup() dupArrIndex = -1 For i = LBound(poArr) To UBound(poArr) dupBool = False For j = LBound(poArr) To i If poArr(i) = poArr(j) And Not i = j Then dupBool = True End If Next j If dupBool = False Then dupArrIndex = dupArrIndex + 1 ReDim Preserve poArrNoDup(dupArrIndex) poArrNoDup(dupArrIndex) = poArr(i) End If Next i eliminateDuplicate = poArrNoDup End Function 

字典最多有255个项目,所以如果你有更多的价值,你需要使用一个集合。 不幸的是,Collection对象没有.Contains(a)或者.Exists(a)方法,但是这个函数通过使用错误号来处理(伪造)它:

更正:字典没有这样的限制(谢谢Zairja)。 我可能一直在使用Integer遍历我的Dictionary。 无论如何,这个函数允许你检查Collections是否存在物品,所以如果它对任何人都有用的话,我会把它留在这里:

 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 

所以,如果你确实需要一个集合,你可能只需要replace

 dict.Exists(strVal) 

 CollContainsItem(coll, strVal) 

并更换

 Set dict = CreateObject("Scripting.Dictionary") 

 Set coll = CreateObject("Scripting.Collection") 

并使用其余的Zairja的代码。 (我没有真正尝试,但它应该是接近的)