调试复制粘贴唯一值的问题

时间:2015-04-03 20:04:46

标签: excel vba excel-vba unique

我在调试一些代码时遇到问题,我一直致力于从工作表(1)中复制来自列AD的唯一值。对于行

aRange.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Worksheets(2).Range("A1"), Unique:=True

我一直收到调试错误:

  

提取范围包含缺少或非法的字段名称。

我错过了什么?

Sub FilteroOutUniquesSerialNumber()

Dim uniquesArray As Variant
Dim LastRow As Variant
Dim aRange As Range
Set aRange = ActiveWorkbook.Worksheets(1).Columns("AD:AD")
Application.ScreenUpdating = False
With Worksheets(2)
    aRange.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Worksheets(2).Range("A1"), Unique:=True
    LastRow = ActiveWorkbook.Worksheets(1).Cells(.Rows.Count, "AD").End(xlUp).Row
    uniquesArray = ActiveWorkbook.Worksheets(1).Range("AD2:AD" & LastRow)
End With
Dim txt As String, i As Integer
For i = 1 To UBound(uniquesArray)
    txt = txt & uniquesArray(i, 1) & ","
Next
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

总有另一种方法可以做。您可以随时创建另一个工作表,复制所需的数据,并使用RemoveDuplicates Excel公式,我认为这个公式更有效,您可以将此代码导入您的代码:

ActiveWorkbook.Worksheets(1).Columns("AD:AD").Copy
ActiveWorkbook.Worksheets(3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveWorkbook.Worksheets(3).CurrentRegion.RemoveDuplicates Columns:=1, Header:=xlNo
uniquesArray = ActiveWorkbook.Worksheets(3).CurrentRegion

执行此类任务后,您始终可以删除内容或整张表格。