VBA code to delete a row based on a non empty cell

2019-09-07 05:27发布

I am running a report of employees who charge time to different codes. The report gives me the following columns:

Emp# / Emp Name / Rate / TermDate

If the employee has left, then there is a value in the TermDate column.

Because the value in the cell could be any date, I want to write a macro that will search the list and delete any row in which the value in the fourth column is NOT blank.

I've found several examples of how to delete a row based on blank cells, or based on certain values, but none on a non-blank value.

Each report will have a different number of rows as well so I need help selecting the range and deleting rows in the range based on the value of the final column.

5条回答
混吃等死
2楼-- · 2019-09-07 05:54

Fastest way. Use .Autofilter. No need to loop...

Sub Sample()
    Dim LRow As Long
    Dim delRange As Range

    With ThisWorkbook.Sheets("Sheet1")
        '~~> Remove any filters
        .AutoFilterMode = False

        LRow = .Range("D" & .Rows.Count).End(xlUp).Row

        With .Range("A1:D" & LRow)
            .AutoFilter Field:=4, Criteria1:="<>"
            Set delRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With

    If Not delRange Is Nothing Then delRange.Delete
End Sub
查看更多
对你真心纯属浪费
3楼-- · 2019-09-07 05:54

My solution would be:

Dim lng_LastRow As Long
Dim lng_i As Long

lng_LastRow = Range("A1").End(xlDown).Row

For lng_i = 1 To lng_LastRow

    If Len(Trim(Cells(lng_i, 4).Value)) > 0 Then
        Rows(lng_i).Delete
        lng_i = lng_i - 1
    End If


Next lng_i
查看更多
Explosion°爆炸
4楼-- · 2019-09-07 05:55

This assumes that the column to check is column D

Sub RowKiller()
    Dim col As String, N As Long, i As Long
    col = "D"
    N = Cells(Rows.Count, col).End(xlUp).Row
    For i = N To 1 Step -1
        If Cells(i, col).Value <> "" Then
            Cells(i, col).EntireRow.Delete
        End If
    Next i
End Sub
查看更多
疯言疯语
5楼-- · 2019-09-07 06:02

If I understand correctly, then you want something like this?

Sub DeleteNonEmptyRows()

  Dim row As Integer, N As Integer

  N = Cells(Rows.Count, "D").End(xlUp).Row

  For row = N To 2 Step -1
      If Not IsEmpty(Range("D" & row)) Range("A" & row).EntireRow.Delete
  Next row

End Sub

It is assumed that TermDate is in column D.

查看更多
做自己的国王
6楼-- · 2019-09-07 06:19

Consider using a filter on the data instead. You didn't mention what version of Excel, but in 2010 go to the data tab, select the termdate column, then click on "filter".

Notice a little dropdown arrow appears in the first cell of the column. Click on that, then deselect all but the "blanks" selection. Wha-la.

That way the data is still there for history if you need it.

Oh and after applying the filter, a little funnel icon will remain in the first cell of the column to show it's a filtered column.

查看更多
登录 后发表回答