首页 > 解决方案 > 如果 A 列文本“客户帐户”和 M 列 <=0 删除之间的所有行

问题描述

在此处输入图像描述在此处输入图像描述

如果满足条件,则尝试删除完整的行。如果 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

标签: excelvba

解决方案


您当前问题的答案可能是您正在使用对当前活动工作表的引用。您甚至声明了父工作表 ( 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

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


推荐阅读