2015-05-13 70 views
1

必需: 我試圖創建過濾細胞I22所有值的宏,選擇所有的那些行,刪除它們,然後再重新篩選。刪除「零」和「N/A」,從過濾器的行 - VBA

我有什麼: 目前我在做這兩個不同的步驟,因爲在一個步驟做這需要幾個小時(因爲它刪除每行排)

碼(1 ):自動過濾器爲'零'和'N/A',選擇它們並清除所有內容。接下來清除過濾器並從最大到最小排序。這樣,excel不需要分別刪除每一行,從而使進程更快。

代碼(2):刪除所有空白行。

我有這樣的印象,考慮到它需要做的任務,這段代碼不是完全有效和太長。是否有可能將這些組合成一個代碼?

碼(1)

Sub clearalldemandzero() 

clearalldemandzero Macro 

ActiveWindow.SmallScroll Down:=15 
Range("A26:EU26").Select 
Selection.AutoFilter 
ActiveWindow.SmallScroll ToRight:=3 
ActiveSheet.Range("$A$26:$EU$5999").AutoFilter Field:=9, Criteria1:="=0.00" _ 
    , Operator:=xlOr, Criteria2:="=#N/A" 
Rows("27:27").Select 
Range("D27").Activate 
Range(Selection, Selection.End(xlDown)).Select 
Selection.Clear 
ActiveSheet.ShowAllData 
Range("H28").Select 
ActiveWorkbook.Worksheets("Solver 4").AutoFilter.Sort.SortFields.Clear 
ActiveWorkbook.Worksheets("Solver 4").AutoFilter.Sort.SortFields.Add Key:= _ 
    Range("I26:I5999"), SortOn:=xlSortOnValues, Order:=xlDescending, _ 
    DataOption:=xlSortNormal 
With ActiveWorkbook.Worksheets("Solver 4").AutoFilter.Sort 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 
End Sub 

碼(2)

Sub DeleteBlankRows3() 

'Deletes the entire row within the selection if the ENTIRE row contains no data.' 

Dim Rw As Range 

If WorksheetFunction.CountA(Selection) = 0 Then 

    MsgBox "No data found", vbOKOnly, "OzGrid.com" 
    Exit Sub 
End If 

With Application 

    .Calculation = xlCalculationManual 
    .ScreenUpdating = False 
    Selection.SpecialCells(xlCellTypeBlanks).Select 

    For Each Rw In Selection.Rows 

     If WorksheetFunction.CountA(Selection.EntireRow) = 0 Then 

      Selection.EntireRow.Delete 
     End If 
    Next Rw 

    .Calculation = xlCalculationAutomatic 
    .ScreenUpdating = True 

End With 

End Sub 
+0

以相反的順序刪除行肯定會有所幫助。 – Bathsheba

+0

如果可以接受,您也可以禁用屏幕更新。這將大大縮短執行時間。在你的'clearalldemandzero'子文件的開始部分放入這個文本'Application.ScreenUpdating = False',然後在子文件末尾放上'Application.ScreenUpdating = true',看看是否有所作爲。基本上,excel將完成所有更改,並在完成後更新屏幕。所以所有的行看起來像是一次刪除。 – andrew

回答

1

如果你的代碼來選擇過濾數據的工作,你可以簡單地刪除所有在一步中的那一排。關鍵是要使用SpecialCells並只能選擇可見的單元格。那麼你可以得到它EntireRowDelete它。

的代碼中的相關行添加會是這樣:

Selection.SpecialCells(xlCellTypeVisible).EntireRow.Delete 

的全部代碼1的修改應該是:

Sub clearalldemandzero() 

    clearalldemandzero Macro 



    ActiveWindow.SmallScroll Down:=15 
    Range("A26:EU26").Select 
    Selection.AutoFilter 
    ActiveWindow.SmallScroll ToRight:=3 
    ActiveSheet.Range("$A$26:$EU$5999").AutoFilter Field:=9, Criteria1:="=0.00" _ 
     , Operator:=xlOr, Criteria2:="=#N/A" 
    Rows("27:27").Select 
    Range("D27").Activate 
    Range(Selection, Selection.End(xlDown)).Select 

    Selection.SpecialCells(xlCellTypeVisible).EntireRow.Delete 

    ActiveSheet.ShowAllData 


End Sub 

作爲一個側面說明,你通常應該努力避免使用SelectSelection和其他與Excel用戶界面接口的東西。我沒有嘗試在這裏解決這些問題,因爲它看起來好像你的代碼通常工作。引用該問題:How to avoid using Select in Excel VBA macros

+0

謝謝!我會盡量修復選擇部分。 – Wolfschmitt