简体   繁体   English

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

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

I don't know much VBA besides googling, copying code, trying (and mostly failing) and am having trouble doing the following.除了谷歌搜索、复制代码、尝试(而且大多失败)之外,我不太了解 VBA 并且在执行以下操作时遇到了麻烦。

I want to delete the entire row if the value in column AF is < 60 and then delete the entire row if the value in column AG < 90 .如果列 AF 中的值 < 60 我想删除整行,然后如果列 AG < 90 中的值删除整行

I am able to do the first part with the following:我可以通过以下方式完成第一部分:

'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

But deleting cells in AG <90 fails with the following code:但删除 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

The first part works (delete cells in AF <60) but the second part does not work and I get the following error: "Run-time error '13' Type mismatch.第一部分有效(删除 AF <60 中的单元格),但第二部分无效,我收到以下错误:“运行时错误 '13' 类型不匹配。

I assume it is a simple fix that I am struggling with because I don't really know VBA.我认为这是一个我正在努力解决的简单修复,因为我真的不知道 VBA。 Any help would be appreciated.任何帮助,将不胜感激。

You probably should combine both rules at the same time and also delete after you loop through everything.您可能应该同时组合这两个规则,并在遍历所有内容后删除。 this will be significantly more effecient.这将大大提高效率。 See below (untested).见下文(未经测试)。

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