0

Within a single macro, I am trying to select a range, name it, and then refer to that range when AutoFiltering data. Here's my code:

'Select and name range
Set bDataDump = ActiveWorkbook
Set DataDump = bDataDump.Sheets(1)    
DataDump.Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFilter
Range(Selection, Selection.End(xlDown)).Select
Set myrange = Selection

'AutoFilter that range for everything but PDC1 and delete visible rows
    'Code fails on next line
DataDump.Range("myrange").AutoFilter field:=11, Criteria1:="<>""PDC1"""
ActiveCell.Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
DataDump.ShowAllData

I get the "Method 'Range' of object '_Worksheet' failed" when I run the macro, and the debugger highlights the first line of the second block of code as the culprit. I have not been able to find any examples on the web of filtering data like this, so I would appreciate any insight as to what I'm doing wrong. Thanks!

Kes Perron
  • 455
  • 5
  • 12
  • 24

3 Answers3

3
DataDump.Range("myrange").AutoFilter field:=11, Criteria1:="<>""PDC1"""

should be

myrange.AutoFilter field:=11, Criteria1:="<>""PDC1"""
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
3

myrange is a Range and not a String. Therefore replace:

DataDump.Range("myrange").AutoFilter field:=11, Criteria1:="<>""PDC1"""

with

myrange.AutoFilter field:=11, Criteria1:="<>""PDC1"""
Gary's Student
  • 95,722
  • 10
  • 59
  • 99
0

For posterity, I present to you my updated code. It includes the replacement of all .Select statements.

Set bDataDump = ActiveWorkbook
Set DataDump = bDataDump.Sheets(1)
Set myrange = DataDump.Range("A1")
Set myrange = Range(myrange, myrange.End(xlToRight))
Set myrange = Range(myrange, myrange.End(xlDown))
'
myrange.AutoFilter field:=12, Criteria1:="<>PDC1"
Set dltrng = DataDump.Range("A2")
Set dltrng = rnage(dltrng, dltrng.End(xlDown))
dltrng.EntireRow.Delete
DataDump.ShowAllData

I find it very strange that the filter part of the recorded macro required doubled quotes

ActiveSheet.Range("$A$1: ... Criteria1:="<>""PDC1"""

but required single quotes when starting with a named range (see line 7 above).

Kes Perron
  • 455
  • 5
  • 12
  • 24