VBA /宏根据值或文本删除行

时间:2016-06-13 14:46:54

标签: vba macros rows

我有这段代码删除所有包含" Service Tower"仅在D列中。我想要的是能够删除更多的行,这些行还包含"流播放","数据集"以及更多包含这些文本的行。它们是在列a,b还是c到z。我希望有人可以帮我编辑我的代码,以便能够添加除#34; Service Tower"以外的更多单词。提前谢谢!

Sheets("database").Select

Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

With ActiveSheet    
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False    

    Firstrow = .UsedRange.Rows(2).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    For Lrow = Lastrow To Firstrow Step -1
        With .Cells(Lrow, "D")
            If Not IsError(.Value) Then
                If .Value = "Service Tower" Then .EntireRow.Delete
            End If
        End With

    Next Lrow
End With

ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .Calculation = CalcMode
End With

MsgBox "Report Completed!"
End Sub

1 个答案:

答案 0 :(得分:0)

If .Value = "Service Tower" Or .Value = "Stream Play" Or .Value = "Data Set" Then .EntireRow.Delete

如果你只有一些人可以使用,这将有效。对于更多数量的项目,最好使用数组:

delArray = Array("Service Tower", "Stream Play", "Data Set") ' add all the values you want in here
For Lrow = Lastrow To Firstrow Step -1
    With .Cells(Lrow, "D")
        For i = 0 to UBound(delArray)  ' arrays are indexed from zero
            If Not IsError(.Value) Then
                If .Value = delArray(i) Then 
                    ' if the value matches an array value we'll enter this condition
                    .EntireRow.Delete 
                    Exit For ' if you deleted the row, don't bother to check it against the next item...
                End If
            End If
        Next
    End With
Next Lrow