如何在所有工作表中自动删除Excel中包含“删除”的所有行?

时间:2017-03-06 00:34:04

标签: excel vba excel-vba

我有不同的表格:

  

"香槟"
       "水"
       " ChocoStrawb"
       "青铜"
       "银"
       "金"
       "铂"
       " PlPlus"
       "大使"

我有这段代码:

Sheets("water").Select
Dim rng As Range, cell_search As Range, del As Range
Set rng = Intersect(Range("A2:A4200"), ActiveSheet.UsedRange)
For Each cell_search In rng
    If (cell_search.Value) = "Delete" Then
        If del Is Nothing Then
            Set del = cell_search
        Else: Set del = Union(del, cell_search)
    End If
End If
Next cell_search
On Error Resume Next
del.EntireRow.Delete

但它仅删除表格中的行" Water"我希望这在所有表格中都有效。

2 个答案:

答案 0 :(得分:2)

您可以创建一个贯穿工作簿中每个工作表的宏:

Sub AllWorkbooks()
Dim WS As Worksheet

For Each WS In ActiveWorkbook.Worksheets
    For x = 4200 To 2 Step -1
        If WS.Cells(x, 1).Value = "Delete" Then
            WS.Rows(x).EntireRow.Delete
        End If
    Next x
Next WS

End Sub

答案 1 :(得分:0)

Autofilter()会加快速度

你可以从一个“处理”传递的worksheet对象的Sub开始:

Sub DeleteRowsWithKeyword(sht As Worksheet, keyWord As String)
    With sht '<--| reference passed sht
        With .Range("A1", .cells(.Rows.Count, 1).End(xlUp)) '<--| reference its column A range form row 1 (header) down to its last not empty row
            .AutoFilter Field:=1, Criteria1:=keyWord '<--| filter cells with passed 'keyWord'
            If Application.WorksheetFunction.Subtotal(103, .cells) > 1 Then .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete  '<--| if any filtered cells other than header then delete their entore row
        End With
        .AutoFilterMode = False
    End With
End Sub

然后你可以让你的“主要”子利用它

  • 循环遍历所有工作表

    Sub Main()
        Dim sht As Worksheet
    
        For Each sht In Worksheets
            DeleteRowsWithKeyword sht, "Delete"
        Next
    End Sub
    
  • 循环显示具有给定名称的所有工作表:

    Sub Main()
        Dim sheetNames As Variant, shtName As Variant
    
        sheetNames = Array("Champagne", "Water", "ChocoStrawb", "Bronze", "Silver", "Gold", "Platinum", "PlPlus", "Ambassador") '<--| list all your relevant sheet names here
        For Each shtName In sheetNames
            DeleteRowsWithKeyword Sheets(shtName), "Delete"
        Next
    End Sub