对象'_Worksheet'的方法'Range'失败 - 命名范围并在VBA中引用它

时间:2013-10-15 20:46:14

标签: excel vba excel-vba range autofilter

在一个宏中,我试图选择一个范围,命名它,然后在自动过滤数据时引用该范围。这是我的代码:

'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

当我运行宏时,我得到对象'_Worksheet'的“方法'范围'失败”,调试器突出显示第二个代码块的第一行作为罪魁祸首。我无法在网上找到这样的过滤数据的任何例子,所以我很欣赏任何有关我做错的见解。谢谢!

3 个答案:

答案 0 :(得分:3)

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

应该是

myrange.AutoFilter field:=11, Criteria1:="<>""PDC1"""

答案 1 :(得分:3)

myrange是一个Range而不是String。因此,替换:

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

myrange.AutoFilter field:=11, Criteria1:="<>""PDC1"""

答案 2 :(得分:0)

对于后人,我向您展示我的更新代码。它包括替换所有.Select语句。

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

我觉得很奇怪,录制的宏的过滤器部分需要加倍的引号

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

但从命名范围开始时需要单引号(参见上面的第7行)。