簡體   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