For循环不捕获所有预期的值

Dim p As Variant For Each p In Range("P2:P8") If p.Value = "TGL block new" Then p.EntireRow.Select Selection.Delete Shift:=xlUp End If Next p 

为什么这个for循环不捕获所有的TGL block new值? 如果任何行在列P2中包含该值:到最后一个单元格,则需要从A2:BL6的数据范围中删除整个水平行

你正在失去p的位置,因为你删除了它,然后当你已经在下一个时候尝试转移到下一个。 删除行时的一般经验法则是从底部开始并进行处理,但这意味着要调整您的方法。

 Dim p As long For p=8 to 2 step -1 If lcase(trim(cells(p, "P").Value)) = "tgl block new" Then cells(p, "P").EntireRow.Delete Shift:=xlUp ' the Shift:=xlUp isn't needed beyond a visual reminder End If Next p 

我已经添加了一些错误控制的值来删除前导/尾随空格和不区分大小写。