对于每个循环结束早,我不明白为什么

我正在寻找一些关于Excel VBA中For Each循环的帮助。

Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!")) For Each SingleCell In ListofCells If ActiveCell.Value = "!!End Measures!!" Then ActiveCell.Offset(1, 0).Select Exit For ElseIf ActiveCell.Value = "" Then ActiveCell.EntireRow.Delete End If Next SingleCell 

由于某种原因,我喜欢早点退出,据我所知,完全没有理由。 在我的电子表格中,我正在寻找从ActiveCell中删除任何未使用的行,直到入口区域结束,我称之为“!! End Measures !!”。 我也试过了:

 Set ListofCells = Range(ActiveCell, ActiveCell.End(xlDown)) 

和它一样的行为。 比预期更早结束循环。

如果我把4个这样的循环连成一行,那么它的工作原理就是这样……但是我希望能够找出为什么这个可能会提早退出,而不是像循环这个4或5次那样做一些奇怪的事情。

任何帮助非常感谢,如果我可以回答任何问题或提供更多的信息,我会很乐意。

有几件事引起了我的注意。

一。 定义你正在循环的内容是很好的。

二。 你在循环中使用Activecell,但我不认为这就是你想要做的,我想你想要SingleCell

三。 删除该行时,您的范围可能会发生变化。 既然你不想要成员,那么重启循环可能会更容易,除非这需要几分钟的时间。 考虑一下:

 Dim ListofCells As Range, SingleCell as Range StartItUp: Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!")) For Each SingleCell In ListofCells.Cells If SingleCell.Value = "!!End Measures!!" Then SingleCell.Offset(1, 0).Select Exit For ElseIf SingleCell.Value = "" Then SingleCell.EntireRow.Delete GoTo StartItUp End If Next SingleCell 

如果您只是试图从ActiveCell中删除所有行到"!!End Measures!!" ,你可以用一行代替现有的代码:

 Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!").Offset(-1, 0)).EntireRow.Delete 

稍微更健壮的版本(不依赖于ActiveCell ,而是简单地删除"!!End Measures!!"和之前的非空白单元格之间的所有行)将是:

 Dim EndMeasures As Range Dim LastMeasure As Range Set EndMeasures = Columns(3).Find("!!End Measures!!") 'Check that there are blank rows before deleting If IsEmpty(EndMeasures.Offset(-1).Value) Then Set LastMeasure = EndMeasures.End(xlUp) Range(LastMeasure.Offset(1), EndMeasures.Offset(-1)).EntireRow.Delete End If