VBA Advanced filter unique values and copy to anot

2019-09-04 13:35发布

I've tried a number of methods to filter a column for unique values (including blanks and blanks with a space inside). I want to filter these values and then paste them into column a in another sheet.

Sub filter_2()
    With Sheets("ICM flags")

        .Columns("a").AdvancedFilter Action:=xlFilterCopy, copytorange:=Sheets("Flag Update (2)").Range("a2"), Unique:=True

    End With
End Sub

The method above works for .range("a2") but if I try to use .range("a1") I get runtime error 1004 advanced filter method of class failed.

I get runtime error 1004 advanced filter method of class failed with the method below.

Sub unique_filter()

               Sheets("ICM flags").Columns("a").AdvancedFilter _
                     Action:=xlFilterCopy, _
                        copytorange:=Sheets("Flag Update (2)").Range("a1"), Unique:=True

End Sub

For both of the above methods and with the edits to Davesexcel answer:

Sub AdvFilter()
Dim ws As Worksheet, sh As Worksheet
Dim rng As Range, Frng As Range

Set sh = Sheets("ICM Flags")
Set Frng = sh.Range("A:A")
Set ws = Sheets("Flag Update (2)")
Set rng = ws.Range("A1")

'Frng.AdvancedFilter Action:=xlFilterCopy, copytorange:=rng, Unique:=True
Frng.AdvancedFilter Action:=xlFilterInPlace, Unique:=True

End Sub

The method works for FilterInPlace but not CopyToRange

3条回答
Viruses.
2楼-- · 2019-09-04 14:17

It seems the problem was being caused by trying to use CopyToRange to copy to another sheet. I have worked around this by first copying to the same sheet then copying these values to the sheet I want them on

Sub AdvFilter() 'filters flags copied from ICM to unique values and pastes  into Flag update sheet.

    Dim ws As Worksheet, sh As Worksheet
    Dim rng As Range, Frng As Range, Prng As Range

    Set ws = Sheets("Flag Update (2)")

    Set sh = Sheets("ICM Flags 1")'destination sheet
    Set Frng = sh.Range("A:A")'filter range
    Set rng = sh.Range("c1")'filter output range


    Frng.AdvancedFilter Action:=xlFilterCopy, copytorange:=rng, Unique:=True
    ws.Columns("a").Value = sh.Columns("c").Value 'Separate copying as the filter didn't like copying to another sheet

End Sub
查看更多
Fickle 薄情
3楼-- · 2019-09-04 14:25

Actually The destination needs to be made the active sheet, then you can get unique values from any other sheet or workbook

查看更多
\"骚年 ilove
4楼-- · 2019-09-04 14:27

When I ran your code, it worked with no errors on my end.

This is the same code but using variables and might work better for you.

Sub AdvFilter()
    Dim ws As Worksheet, sh As Worksheet
    Dim rng As Range, Frng As Range

    Set ws = Sheets("Flag Update (2)")
    Set rng = ws.Range("A1")
    Set sh = Sheets("ICM flags")
    Set Frng = sh.Range("A:A")

    Frng.AdvancedFilter Action:=xlFilterCopy, copytorange:=rng, Unique:=True

End Sub
查看更多
登录 后发表回答