如何基于3列中的值删除工作表中的行

问题描述 投票:0回答:1

如果同一行的C列,D列,E列的列值的总和为零,则必须删除一行。例如。

      ColumnA   Column B   ColumnC   ColumnD    ColumnE
 row1-    abc        xyz         0       abs        abx
 row2-    wqe        tuy         0         0          0
 row3    uhiu        khj       kjh       khk          0

这里我仅由于所有列c,D,E的值为零而必须删除第2行

请帮助

vba excel-vba
1个回答
0
投票

反向循环应该可以完成这项工作。请尝试以下:

Option Explicit

Public Sub DeleteRows()
    Dim i As Long, count As Long, lastRow As Long

    ' Replace Sheet1 with your sheetname
    With ThisWorkbook.Worksheets("Sheet1")

        ' Change C with your most consistent column letter
        ' (a column that has data always to make sure there's no possibility to miss the last row due to empty cells)
        lastRow = .Cells(.Rows.count, "C").End(xlUp).Row

        ' We do a reverse loop to not screw up the index
        For i = lastRow To 2 Step -1

            ' If the cells are empty the "=0" condition will pass, hence the vbnullstring check - I know it looks a bit ugly
            If (.Range("C" & i).Value <> vbNullString And .Range("C" & i).Value = 0) And _
                (.Range("D" & i).Value <> vbNullString And .Range("D" & i).Value = 0) And _
                (.Range("E" & i).Value <> vbNullString And .Range("E" & i).Value = 0) Then

                .Range("C" & i).EntireRow.Delete
                count = count + 1
            End If
        Next i
    End With

    ' Display some message
    If count > 0 Then
        MsgBox "Done!" & vbCrLf & "Deleted " & count & " row(s).", vbInformation + vbOKOnly, "Success"
    Else
        MsgBox "No matches found for deletion", vbInformation + vbOKOnly, "Success"
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.