Delete Specific rows in Excel

后端 未结 2 1709
轮回少年
轮回少年 2021-01-26 00:14

I want to create a for loop to check all of the rows in a sheet that I have and want this code to be able to delete rows if they contain a specified content in certain columns (

相关标签:
2条回答
  • 2021-01-26 00:57

    As a general rule of thumb, you should avoid looping over cells if possible in Excel VBA. Looping over cells is slow and inefficient. It may not matter given the scope of your program, but it is something to be considered. If you are new to VBA programming, it's especially important to pick up good habits early on.

    Here is a solution using the Range.Find method (MSDN reference) to gather the range of rows to delete, and then delete them all in one statement.

    Sub DeleteRows()
    
        Dim rngResults As Range, rngToDelete As Range
        Dim strFirstAddress As String
    
        With Worksheets("Sheet1").UsedRange 'Adjust to your particular worksheet
    
            Set rngResults = .Cells.Find(What:="June") 'Adjust what you want it to find
            If Not rngResults Is Nothing Then
    
                Set rngToDelete = rngResults
    
                strFirstAddress = rngResults.Address
    
                Set rngResults = .FindNext(After:=rngResults)
    
                Do Until rngResults.Address = strFirstAddress
                    Set rngToDelete = Application.Union(rngToDelete, rngResults)
                    Set rngResults = .FindNext(After:=rngResults)
                Loop
    
            End If
    
        End With
    
        If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
    
        Set rngResults = Nothing
    
    End Sub
    
    0 讨论(0)
  • 2021-01-26 01:03

    This will process rows 2 thru 4000, adjust to suit your needs:

    Sub RowKiller()
        Dim K As Range, rKill As Range
        Set K = Range("K2:K4000")
        Set rKill = Nothing
        For Each r In K
            v = r.Text
            If InStr(1, v, "June") > 0 Then
                If rKill Is Nothing Then
                    Set rKill = r
                Else
                    Set rKill = Union(r, rKill)
                End If
            End If
        Next r
    
        If Not rKill Is Nothing Then
            rKill.EntireRow.Delete
        End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题