excel - (VBA)如果单元格 X 小于则删除整行,如果单元格 Y 小于则删除整行
问题描述
除了谷歌搜索、复制代码、尝试(而且大多失败)之外,我对 VBA 了解不多,并且在执行以下操作时遇到了麻烦。
如果列 AF 中的值 < 60我想删除整行,然后如果列 AG < 90 中的值删除整行。
我可以通过以下方式完成第一部分:
'get last row in column AF
Last = Cells(Rows.Count, "AF").End(xlUp).Row
For i = Last To 1 Step -1
'if cell value is less than 60
If (Cells(i, "AF").Value) < 60 Then
'delete entire row
Cells(i, "AF").EntireRow.Delete
End If
Next i
但删除 AG <90 中的单元格失败,代码如下:
'get last row in column AG
Last = Cells(Rows.Count, "AG").End(xlUp).Row
For i = Last To 1 Step -1
'if cell value is less than 90
If (Cells(i, "AG").Value) < 90 Then
'delete entire row
Cells(i, "AG").EntireRow.Delete
End If
Next i
第一部分有效(删除 AF <60 中的单元格),但第二部分无效,我收到以下错误:“运行时错误 '13' 类型不匹配。
我认为这是一个我正在努力解决的简单问题,因为我并不真正了解 VBA。任何帮助,将不胜感激。
解决方案
您可能应该同时组合这两个规则,并在遍历所有内容后删除。这将大大提高效率。见下文(未经测试)。
Sub DeleteSomeRows()
Dim killRange As Range
Dim the90Column As Long, the60Column As Long, i As Long, Last As Long
the90Column = Range("AG1").Column
the60Column = Range("AF1").Column
Last = Cells(Rows.Count, "AG").End(xlUp).Row
For i = Last To 1 Step -1
'if cell value is less than 90
If Cells(i, the90Column).Value < 90 Or Cells(i, the60Column).Value < 60 Then
If killRange Is Nothing Then
Set killRange = Cells(i, 1).EntireRow
Else
Set killRange = Union(killRange, Cells(i, 1).EntireRow)
End If
End If
Next i
If Not killRange Is Nothing Then
killRange.Delete
End If
End Sub
推荐阅读
- c# - DynamicRouteValueTransformer 不存在
- c# - 如何将以下 Xml 转换为 C# 对象
- here-api - HERE.com Places API,“缺少 ApiKey”错误消息,但不是
- javascript - 处理来自 pouchdb 文档的结果
- javascript - 如何在第一个反应组件中添加图像并使用地图功能在其余组件中忽略
- c# - 如何对 QueryString 中包含特殊字符的 Url 进行编码和解码?
- ssh - 如何通过 SSH 连接到 GKE 节点(私有/公共)?
- c# - 偶发性 MessageLockLostException 但锁未过期并且是相同的 MessageReceiver 实例
- reactjs - 使用 react-scripts 代理 websocket 不起作用
- ios - 在 iOS 上使用 Appium 生成代码覆盖率