从列中删除重复项但在另一个工作表上创建列是VBA的结果

时间:2014-05-29 14:26:36

标签: excel vba excel-vba

所以我试图从列中删除重复的ID并将结果粘贴到另一个工作表上。我目前的解决方法是首先将整个列复制到新工作表并删除那里的重复项,但现在非常费力,因为有60k行,我现在想要为多个列执行此操作。

问题:有没有更好的方法来做到这一点,所以我不必先复制列。

这是我目前的代码。

Dim ws As Worksheet
Dim ws2 As Worksheet
Dim wb As Workbook
Set wb = Workbooks("Test.xlsx")
Set ws = wb.Worksheets(1)
Set ws2 = wb.Worksheets(4)

ws.Range("A1:A" & rowz) = ws2.Range("A1:A" & rowz)

with ws2
Set CtrlID = ws2.Range("A1:A" & rowz)
CtrlID.RemoveDuplicates Columns:=1, Header:=xlYes
end with

1 个答案:

答案 0 :(得分:1)

如果您在实施词典方法时遇到问题,可以试试这个:

Dim ws As Worksheet
Dim ws2 As Worksheet
Dim wb As Workbook
Dim dict as Object
Dim r as Range
Set wb = Workbooks("Test.xlsx")
Set ws = wb.Worksheets(1)
Set ws2 = wb.Worksheets(4)

Set dict = CreateObject("Scripting.Dictionary")

'Assign each value to the dictionary
' overwrites existing values and ensures no duplicates
For each r in ws.Range("A1:A" & rowz).Cells
    dict(r.Value) = r.Value
Next

'## Put the dictionary in to the other worksheet:
ws2.Range("A1").Resize(Ubound(dict.Keys) + 1, 1).Value = Application.Transpose(dict.Keys)

Set dict = Nothing

然而我真的没有理由重新发明轮子。您可以运行一些测试来查看哪个更快。