Delete Entire Rows Based on Cell Values

后端 未结 3 537
夕颜
夕颜 2021-02-06 13:00

I want in Excel (2003) to take an imported data dump and format it into a report. Most of what I have done has involved recording a macro and then customizing the code where ne

相关标签:
3条回答
  • 2021-02-06 13:27

    I used this in one of my task, where as I had array of test data of 100 iteration, which I want to trim to first 10 iteration, so I used the "iteration# > 10" cells to delete entire row.

    Sub trim_row()
    
    ' trim_row Macro
    ' to trim row which is greater than iteration#10
    
    Dim RowToTest As Long
    Dim temp As String
    Dim temp1 As Integer
    
    For RowToTest = Cells(Rows.Count, 6).End(xlUp).Row To 2 Step -1
    
    With Cells(RowToTest, 6)
    
    temp = .Value
    If temp = "" Then
    
        Else
        temp1 = Trim(Replace(temp, "Iteration# :: ", ""))
    
            If temp1 > 10 Then
            Rows(RowToTest).EntireRow.Delete
            End If
    End If
    
    End With
    
    Next RowToTest
    
    End Sub
    

    I user replace & trip to extract number from the string, and introduced the if = "" condition to skip the empty rows. I had empty row separating to set of test data.

    0 讨论(0)
  • 2021-02-06 13:33

    I agree with @Tim_Williams that you need to work backwards as that seems to be the issue. I would do something like this.

    Sub Main()
    Dim workrange As Range
    Dim Firstrow As Integer
    Dim Lastrow As Integer
    Dim lrow As Integer
    
    'Find first and last used row in column D
    Range("D:D").Select
    Firstrow = ActiveSheet.UsedRange.Cells(1).Row
    Lastrow = ActiveSheet.Range("D1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
    
    'Loop through used cells backwards and delete if needed
    For lrow = Lastrow To Firstrow Step -1
        Set workrange = Cells(lrow, 4)
        If workrange.Value <> "VFIRE" _
            And workrange.Value <> "ILBURN" _
            And workrange.Value <> "SMOKEA" _
            And workrange.Value <> "ST3" _
            And workrange.Value <> "TA1PED" _
            And workrange.Value <> "UN1" _
                Then workrange.EntireRow.Delete
    
    Next lrow
    
    End Sub
    
    0 讨论(0)
  • 2021-02-06 13:47

    I'm all about brevity.

    Sub DeleteRowBasedOnCriteria()
    Dim RowToTest As Long
    
    For RowToTest = Cells(Rows.Count, 4).End(xlUp).Row To 2 Step -1
    
    With Cells(RowToTest, 4)
        If .Value <> "VFIRE" _
        And .Value <> "ILBURN" _
        And .Value <> "SMOKEA" _
        And .Value <> "ST3" _
        And .Value <> "TA1PED" _
        And .Value <> "UN1" _
        Then _
        Rows(RowToTest).EntireRow.Delete
    End With
    
    Next RowToTest
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题