且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Excel中删除特定行

更新时间:2023-12-03 18:55:04

拇指,如果可能,应避免在Excel VBA中循环单元格。遍历单元格是缓慢而低效的。鉴于程序的范围,这可能并不重要,但这是需要考虑的事情。如果您不熟悉VBA编程,那么尽早养成良好的习惯就尤其重要。

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.

这里是使用 Range.Find 方法( MSDN参考)收集要删除的行范围,然后在一条语句中将其全部删除。

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