如果列A文本“客户帐户”和列M <= 0,则删除之间的所有行

时间:2019-10-29 12:11:27

标签: excel vba

enter image description here enter image description here

如果符合条件,则尝试删除完整的行。如果列A具有文本“客户帐户”,列M <= 0,则删除之间的所有行。 它不会给出任何错误,但不会删除行

Dim sh As Worksheet

Set sh = Sheets("RAW DATA FILE")

Dim x As Long, lastrow As Long
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For x = lastrow To 1 Step -1
    If Cells(x, 2).Value = "customer account" And Cells(x, 13) <= 0 Then
        Rows(x).Delete
    End If
Next x

2 个答案:

答案 0 :(得分:1)

当前问题的答案可能是您正在使用对当前活动工作表的引用。您只是声明了父工作表(sh),但从未如此使用过。您可以通过简单的With克服这一点:

Dim sh As Worksheet: Set sh = Sheets("RAW DATA FILE")
Dim x As Long, lastrow As Long

With sh
    lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    For x = lastrow To 1 Step -1
        If .Cells(x, 2).Value = "customer account" And .Cells(x, 13) <= 0 Then
            .Rows(x).Delete
        End If
    Next x
End with

这使问题变得更加棘手,是否有更好,更快的方法来获得结果。按照@BigBen,您应该考虑使用过滤器。您可以尝试:

Dim sh As Worksheet: Set sh = Sheets("RAW DATA FILE")
Dim lastrow As Long
Dim rng As Range

With sh
    lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    Set rng = .Range("A1:M" & lastrow)
    rng.AutoFilter Field:=2, Criteria1:="customer account"
    rng.AutoFilter Field:=13, Criteria1:="<=0"
    rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    rng.AutoFilter
End With

这是假设您正在使用标题行。


编辑:

如果您打算删除整个范围的行,则不再选择AutoFilter。在那种情况下,循环就可以解决问题,但是您需要一些Offset来检查列M的值:

Dim sh As Worksheet: Set sh = Sheets("Blad1")
Dim x As Long, lastrow As Long

With sh
    lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    For x = lastrow To 1 Step -1
        If .Cells(x, 2).Value = "customer account" And .Cells(x, 13).Offset(4, 0) <= 0 Then
            .Range(x & ":" & x + 4).EntireRow.Delete
        End If
    Next x
End With

这将删除AND选中的行之间的行。如果这不是您想要的,则应使用:.Range(x+1 & ":" & x + 3).EntireRow.Delete

答案 1 :(得分:0)

尝试以下

Dim sh As Worksheet
Set sh = Sheets("RAW DATA FILE")
Dim x As Long, lastrow As Long
lastrow = sh.Cells(Rows.Count, 1).End(xlUp).Row
For x = lastrow To 1 Step -1
    If sh.Cells(x, 1).Value = "customer account" And sh.Cells(x, 13) <= 0 Then
        sh.Rows(x).Delete
    End If
Next x