excel 删除除具有特定值的行以外的所有行

mnemlml8  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(228)

如何根据列值保留某些行并删除其余行?
现在我重复我想删除的值。

With ActiveSheet
    FirstRow = 4
    LastRow = 10000

    For Row = LastRow To FirstRow Step -1
        If .Range("A" & Row).Value = "ITT1" Then
            .Range("A" & Row).EntireRow.Delete
        End If
    Next Row
End With
lyr7nygr

lyr7nygr1#

你需要使用<>Not来否定你的If语句:
就用

If .Range("A" & Row).Value <> "ITT1" Then

If Not .Range("A" & Row).Value = "ITT1" Then

删除除列A中值为ITT1的行以外的所有行。
请注意,与硬编码最后一行LastRow = 10000不同,您可以使用以下命令来确定它:

LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row  ' get last used row in column A

因此,如果只有100行,则循环不会从10000开始,而只是在实际有数据的行上循环。
所以它应该看起来像这样:

With ActiveSheet
    Const FirstRow As Long = 4

    Dim LastRow As Long
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row  ' get last used row in column A

    Dim Row As Long
    For Row = LastRow To FirstRow Step - 1
        If Not .Range("A" & Row).Value = "ITT1" Then
            .Range("A" & Row).EntireRow.Delete
        End If
    Next Row
End With

如果它必须删除很多行,这可能会有点慢。所以我建议使用Union将要删除的行收集在一个变量中,并在最后一次性删除它们,这是快得多

With ActiveSheet
    Const FirstRow As Long = 4

    Dim LastRow As Long
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row  ' get last used row in column A

    Dim RowsToDelete As Range  ' here we collect which rows to delete

    Dim Row As Long
    For Row = LastRow To FirstRow Step - 1
        If Not .Range("A" & Row).Value = "ITT1" Then
            If RowsToDelete Is Nothing Then
                ' set first row
                Set RowsToDelete = .Range("A" & Row).EntireRow
            Else
                ' add all the other rows
                Set RowsToDelete = Application.Union(RowsToDelete, .Range("A" & Row).EntireRow)
            End If
        End If
    Next Row

    If Not RowsToDelete Is Nothing Then
        RowsToDelete.Delete
    Else
        MsgBox "No rows to delete were found."
    End If
End With

如果你首先收集一个变量中所有要删除的行,你甚至不需要向后运行循环Step - 1,如果你喜欢,只需要使用一个正常的向前循环:

For Row = FirstRow To LastRow

相关问题