【发布时间】:2020-02-15 11:22:22
【问题描述】:
通常,我会使用带有行号的 For 循环通过向后工作来删除行,这看起来类似于:
For rowIndex = 10 to 1 Step (-1)
'delete Row with current row index
next rowIndex
在指定单元格范围内循环时如何执行此操作?下面的代码显然是行不通的(当执行删除命令时,它将在下一次迭代中跳过一个单元格/行,检查here 或here):
Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
'check for some condition e.g. based (but not limited to) the singleCell's value
If condition = True then
singleCell.EntireRow.Delete
'Note: the deletion has to be done before the next loop-iteration starts
'Unfortunately, this makes solutions like working with Union unfeasible
End If
Next singleCell
有没有人知道如何在不切换到“Backward-Row-Number-Loop”的情况下使第二个代码块工作(参见第一个代码块)?有没有办法以某种方式将 singleCell 指针/计数器“重置”为新值,以便循环不会跳过下一个单元格/行?或任何其他替代方案(如使 Range-Loop 向后工作等)?任何解决方案的提示都将不胜感激,代码也被剪断,但如果有必要我可以不用。
我必须避免将不需要的行添加到数组(范围等)中,并在循环完成后删除整个数组。不幸的是,作为实现的条件,必须在评估下一个单元格之前删除该行。
基本上可能存在这样一种情况,即应该删除哪些行的两个单元格将位于同一行中。在这种情况下,第二个单元格将在被检查之前被删除,这是理想的行为。解决方案不必但应该可以扩展以包含这种情况。
编辑:我正在考虑的另一个解决方案是在执行 For-Loop (see here) 之前反转范围,但到目前为止我还没有尝试过。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
您可以使用相同的第一个代码 For rowIndex = 10 to 1 Step (-1) for somerange 也可以作为
For rowIndex = somerange.rows.count to 1 Step (-1) -
@Naresh 谢谢,但这不是一个选项,请参阅我的问题:
without switching to a "Backward-Row-Number-Loop"