2017-10-06 101 views
0

想要根据列M中的数据删除报表中的行。报表具有可变大小的行方式,但列中的宽度相同。单元中的“有效”意味着它被删除。基于列中的值的VBA Excel删除行

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

不要活动单元格的工作。你没有使用你的'cell'迭代器变量,从那开始。 –

+0

此外,我**高度**建议不循环列中的所有行。最大限度地减少范围,这将有所帮助。 – BruceWayne

回答

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 
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