excel - 如果 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
解决方案
您当前问题的答案可能是您正在使用对当前活动工作表的引用。您甚至声明了父工作表 ( 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
推荐阅读
- php - 如何将 url 参数更改为斜杠?
- ruby-on-rails - Ruby on rails:捆绑更新在 Windows 中出现错误
- powershell - 通过 Docker API 在正在运行的容器中执行 powershell 命令
- python - 同时显示多个openCV图像
- neo4j - 用一个关系替换从一个节点到另一个节点的关系
- excel - VBA - Excel 列表框 - 将项目添加到第二个列表框时查找重复项
- angular - Mat-chip-list 的电子邮件验证
- java - 如何检查Java进程中是否加载了一个类
- c# - 如何在两端通过 UDP 和后处理数据报连续发送和接收(使用相同的套接字?)
- python - df.style.apply 在显示中居中显示多索引值