基于列中的值的VBA Excel删除行

希望根据列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 

它现在关于ActiveCell但在“M:M”列中的单元格。 另外,你需要从底层开始(不是显而易见的)。 所以,假设有比10000更less的行,你需要像这样的东西:

 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 

我find了一个使用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