Delete Specific rows in Excel

后端 未结 2 1708
轮回少年
轮回少年 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
    

提交回复
热议问题