繁体   English   中英

(VBA)如果单元格 X 小于则删除整行,如果单元格 Y 小于则删除整行

[英](VBA) Delete entire row if cell X is less than AND delete entire row if cell Y is less than

除了谷歌搜索、复制代码、尝试(而且大多失败)之外,我不太了解 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM