VBA Excel基于列中的值删除行

时间:2017-10-06 21:02:15

标签: excel vba excel-vba

想要根据列M中的数据从报表中删除行。报表的行大小可变,但列的宽度相同。单元格中的“有效”表示它被删除。

Sub Create()
Dim Range1 As Range
Set Range1 = Range("M:M")
For Each cell In Range1
    If ActiveCell.Value = "Valid" _
    Then ActiveCell.EntireRow.Delete
Next cell
End Sub

2 个答案:

答案 0 :(得分:1)

现在关于ActiveCell但是列中的单元格" M:M"。此外,你需要从下往上开始(不明显但真实)。所以,假设行数少于10000,你需要这样的东西:

Sub Create()
    Dim LastRow As Long
    Dim i As Long

    LastRow = Range("M10000").End(xlUp).Row
    For i = LastRow To 1 Step -1
        If Range("M" & i) = "Valid" Then
            Range("M" & i).EntireRow.Delete
        End If
    Next
End Sub

答案 1 :(得分:0)

我找到了使用For Each的方法:

Public Sub Create()
Dim Range1 As Range
Dim Cell
Dim LastRow As Long

    Set Range1 = Range("M1")
    ' assume, there is some data in the first row of your sheet
    LastRow = Range1.CurrentRegion.Rows.Count
    ' otherwise, find last cell in column M with a value, assume before row 10000
    LastRow = Range("M10000").End(xlUp).Row

    ' select the cells to process
    Set Range1 = Range(Range1, Range1.Offset(LastRow, 0))

    ' process the rows
    For Each Cell In Range1
        If Cell.Value = "Valid" Then
            Debug.Print "' delete row from at address :: " & Cell.Address
            Range(Cell.Address).EntireRow.Delete
        End If
    Next
End Sub