Eliminating duplicates from a list and copying result into separate worksheet using VBA

时间:2015-08-07 01:30:59

标签: excel vba excel-vba worksheet

I am here because I need help with the task stated above. At my student worker job we have a list of customers in a column of a spreadsheet that we add to whenever we take in job orders. What I need help with is basically transferring over a weeded out version (no duplicates) of this list into a different spreadsheet with a total number of entries.

My boss gave me this job because I was messing around with other aspects of VBA code in my spare time and he noticed. Unfortunately, I'm not entirely 100% sure how to do this since I'm pretty new to the language.

Here is what I have so far (note it doesn't work) http://pastebin.com/E3bKbr24

Any help would be greatly appreciated and especially pointers on how to make this more efficient! I know C++ and I know that the double nested For loop is very inefficient so any suggested ways to improve the performance of this function would be helpful (especially since it will be called a lot).

Thanks again!

2 个答案:

答案 0 :(得分:1)

这是我的建议:

Sub Copy()

    Worksheets("originalsheet").Columns("Q:Q").Copy Destination:=Worksheets("newsheet").Columns("Q:Q")
    Worksheets("newsheet").Columns("Q:Q").RemoveDuplicates Columns:=1, Header:=xlYes

End Sub

将“originalsheet”替换为您尝试从中复制数据的工作表的名称,并将“newsheet”替换为您尝试将数据复制到的新工作表的名称。您还可以将列中的Q替换为更宽的范围,例如“C:S”,如果这是您需要的。

如果您想将所有内容保存在同一工作表中并根据需要重新使用该工作表,最好在外部创建一个而不是在子中创建一个新工作表,否则最终会得到一个新工作表每次你启动子。

答案 1 :(得分:0)

Excel has an inbuilt remove duplicates function (Data / Remove duplicates)

You can use it programmatically like so (Very basic example but should give you the hints to incorporate into your code):

Sub CopyUnique()
    Columns("Q:Q").Copy 'Copy column Q
    Workbooks.Add 'Add a workbook
    ActiveSheet.Paste ' Paste
    ActiveSheet.Range("$A:$A").RemoveDuplicates Columns:=1, Header:=xlYes 'remove dupes
End Sub