问题
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!
回答1:
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"""
回答2:
DataDump.Range("myrange").AutoFilter field:=11, Criteria1:="<>""PDC1"""
should be
myrange.AutoFilter field:=11, Criteria1:="<>""PDC1"""
回答3:
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).
来源:https://stackoverflow.com/questions/19390732/method-range-of-object-worksheet-failed-naming-range-and-referring-to-it