I have a routine that copies the visible cells in an autofilter range to another sheet, based on the criteria of how much data is revealed by the autofilter. I use this routine multiple times, and it works without a hitch, except in this instance. In this instance, it copies all of the available data, not only the visible cells. I've been trying to find out what the problem is, to no avail, and so am asking for help.
The code is below. The macro first filters column P, and pulls up anything that's not "UNAU". Then it filters column M for anything other than "G" or "E". The expected result is that nothing will be found, and that's what happens in this case. So, my autofilter is only displaying the headings. There's a test (Lcount) to see if the # of visible cells (including headers) is less than or greater than 20. If less, nothing is copied. If more, all of the visible cells, except for the headers, are supposed to be copied and pasted into my "Results" worksheet. But for some reason, even though the autofilter displays no results, my "Results" page is filled with ALL of the data that the autofilter is filtering on.
Help! It's driving me crazy!
Sub Test()
Dim DstWkb As Workbook
Dim rng As Range
Dim RngEnd As Range
Dim cell As Range
Dim NumRows As Variant
Dim lcount As Variant
Dim rTable As Range
Set rng = Selection
Set DstWkb = Workbooks("Active Position Checklist.xls")
DstWkb.Worksheets("APRData").Select
With DstWkb.Worksheets("APRData")
'Restrain the filter to cells from A1 to the last entry in column Q
Set rng = .Range("A1:Q1")
Set RngEnd = .Cells(Rows.Count, rng.Column).End(xlUp)
Set rng = IIf(RngEnd.Row < rng.Row, rng, .Range(rng, RngEnd))
'3) Test to see if UNAU doesn't have a G or E
rng.EntireRow.AutoFilter Field:=16, Criteria1:="=UNAU", Operator:=xlAnd
rng.EntireRow.AutoFilter Field:=13, Criteria1:="<>G", Operator:=xlAnd, _
Criteria2:="<>E"
'See whether there's data or not
lcount = .AutoFilter.Range.Rows.SpecialCells(xlCellTypeVisible).Count
If lcount > 20 Then
'Copy and paste only the filtered data
Set rTable = Sheets("APRData").AutoFilter.Range
Set rTable = rTable.Resize(rTable.Rows.Count - 1)
'Move new range down to start at the first data row.
Set rTable = rTable.Offset(1)
rTable.Copy Destination:=DstWkb.Worksheets("Results").Range("A65536").End(xlUp).Offset(1, 0)
End If
End With
End Sub
Bookmarks