如何根据VBA中2列的条件删除行?

时间:2015-05-05 14:35:10

标签: excel-vba vba excel

我需要通过删除具有我们不与之合作的特定位置的行来清理某些记录。我想弄清楚如何编写将搜索目标城市和目的地状态列的VBA代码(在我当前的情况下为L& M列)并删除与特定城市和州相匹配的记录。

我已经想出了如何在同一列中删除多个条件的记录,但不是跨列。

With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With
With Sheets("data_export")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Firstrow = 2
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
    For lRow = Lastrow To Firstrow Step -1
        With .Cells(lRow, "D") 'Stops'
            If Not IsError(.Value) Then
                If .Value >= "1" Then .EntireRow.Delete
            End If
        End With

        With .Cells(lRow, "P") 'HaZMat
            If Not IsError(.Value) Then
                If .Value <> "" Then .EntireRow.Delete
            End If
        End With

        With .Cells(lRow, "T") 'Service
            If Not IsError(.Value) Then
                If .Value <> "Truck Load" Then .EntireRow.Delete
            End If
        End With
    Next lRow
End With

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

1 个答案:

答案 0 :(得分:1)

使用以下数据:

enter image description here

我们要删除 Springfield,California 的所有行,但保留佛罗里达州斯普林菲尔德。

Sub RowKiller()
    Dim N As Long, i As Long
    N = Cells(Rows.Count, "L").End(xlUp).Row
    For i = N To 1 Step -1
        If Cells(i, "L") = "Springfield" And Cells(i, "M") = "California" Then
            Cells(i, "L").EntireRow.Delete
        End If
    Next i
End Sub