使用vba通过列循环高级过滤器

时间:2017-03-30 22:01:14

标签: excel vba excel-vba

对于vba,我是新手,所以请耐心等待。我有一个在列和行长度上可变的数据集。每列都包含一系列数据,我正在尝试使用高级过滤器来输出唯一的单元格。

sub uniques()
    dim i as integer
    dim numcol as integer
    dim rng as range
    dim ws as worksheet
    dim ws2 as worksheet

    set ws = sheets("Sheet1") 'data
    set ws2 = sheets("Sheet2") 'paste unique per column data

    numcol = activesheet.usedrange.columns.count

    for i = 1 to numcol

        set rng = ws.columns(i)
        set rng2 = ws2.columns(i)

        ws.rng.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=ws2.rng2, unique=True

    Next

end sub

我尝试了几种不同的方法,但我认为这是最接近的方式。我渴望学习,所以任何提示都非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我想我的问题是在循环中正确设置复制和粘贴范围。这有效。我很欣赏这个评论。

Sub test()
    Dim i As Integer
    Dim numcol As Integer
    Dim rng As Range
    Dim ws As Worksheet
    Dim ws2 As Worksheet

    Set ws = ActiveSheet 'data
    Set ws2 = Sheets.Add 

    numcol = ws.UsedRange.Columns.count
    Set rng = ws.UsedRange

    For i = 1 To numcol
        rng.Columns(i).AdvancedFilter Action:=xlFilterCopy,  CopyToRange:=ws2.Columns(i), Unique:=True
    Next

End Sub