VBA - Autofilter and copy visiable data to another feild

161 views Asked by At

I have a dataset where I want to the VBA to do an auto-filter and in column B just unselect 0 and keep all the other values.

Then copy the visible cells to a new sheet. Can someone help me what the error is

Thanks

Sub findlastrowwithvaluefilter()
ActiveWorkbook.Sheets("CASCADE -Offshore Upload Format").Activate

LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

    With Range("A1:Q" & LastRow)
        .AutoFilter
        .AutoFilter Field:=2, Criteria1:="Select All", Operator:=xlAnd, Criteria1:="<>0"

        End With

    Range("A2:Q" & LastRow).Select
    ActiveSheet.Range("A1:Q1" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy
    Sheets("Sheet1").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

MsgBox (LastRow)

End Sub
2

There are 2 answers

2
TylerDurden On BEST ANSWER

Replace

.AutoFilter Field:=2, Criteria1:="Select All", Operator:=xlAnd, Criteria1:="<>0"

with

.AutoFilter Field:=2, Criteria1:="<>0", Operator:=xlAnd

and should work

0
Brian On

it was a very small syntax issue. below is the working code.

The way to write the criteria so that zero is filtered out is

Criteria1:="<>0". the = sign should be outside the parenthesis.

    Sub findlastrowwithvaluefilter()
ActiveWorkbook.Sheets("CASCADE -Offshore Upload Format").Activate

LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row


    With Range("A1:Q" & LastRow)
        .AutoFilter
        .AutoFilter Field:=2, Criteria1:="<>0", Operator:=xlAnd
        End With

    Range("A2:Q" & LastRow).Select
    ActiveSheet.Range("A1:Q1" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy
    Sheets("Sheet1").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

MsgBox (LastRow)

End Sub