2013-10-15 155 views
0

在一個單獨的宏,我想選擇一個範圍,名稱,然後自動篩選數據時,請參考該範圍。這裏是我的代碼:Method對象的「範圍」「_Worksheet」失敗 - 命名範圍,並提到它在VBA

'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’失敗」當我運行宏,調試器突出了代碼的第二塊作爲罪魁禍首的第一道防線。我一直沒能在這樣的過濾數據網頁上找到任何示例,所以我很感謝任何有關我在做什麼錯誤的見解。謝謝!

+5

哇 - 更多'Select's比行代碼 - [亞洲時報Siddharth潰敗(http://stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select)不會批准! – pnuts

+0

笑@ PNUTS:你讓我看起來像一個魔鬼:):@SMPerron [有趣的閱讀](http://stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select) –

+1

@pnuts:哦,你已經提到了這個鏈接。糟糕... –

回答

3

myrange是一個範圍,而不是一個字符串。因此取代:

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

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

+ 1用於解釋問題:) –

+0

現在變得非常有意義。謝謝! –

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

應該

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

+ 1 for first in:p –

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 

我覺得很奇怪,有一個命名的範圍(見上文第7行)啓動時所需的錄製宏的過濾器部分翻倍行情

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

,但需要單引號。

相關問題