[英]VBA delete cell in for each loop
I'm trying to delete every cell, and a cell to the left of it, if the value of the cell is 0. (Also, to set the interior color to no fill if the value of the cell is greater than 0.)如果单元格的值为 0,我试图删除每个单元格及其左侧的单元格。(另外,如果单元格的值大于 0,则将内部颜色设置为无填充。)
This is my code so far到目前为止,这是我的代码
For Each cell In Range("I2:I" & LastTransaction)
If cell.Value = 0 Then
Range(cell.Offset(0, -1).Address, cell.Address).Delete Shift:=xlUp
ElseIf cell.Value > 0 Then
cell.Interior.ColorIndex = 0
End If
Next cell
The problem here is that, every time the cells are deleted, AND SHIFTED UPWARDS, the for each loop doesn't take the upward shift into account, and skips the next cell in the range.这里的问题是,每次删除单元格并向上移动时,for each 循环都不考虑向上移动,并跳过范围内的下一个单元格。
As per @JvdV's comment, when deleting in a loop you need to do it back to front (or in this case bottom to top), using Step -1
.根据@JvdV 的评论,在循环中删除时,您需要使用
Step -1
从头到尾(或在本例中是从下到上)进行删除。
In this case your For loop would look something like;在这种情况下,您的 For 循环看起来像;
For x = LastTransaction to 2 Step -1
If Range("I" & x).Value = 0 then
Range("H" & x & ":I" & x).Delete Shift:=xlUp
ElseIf Range("I" & x).Value > 0 Then
Range("I" & x).Interior.ColorIndex = 0
End If
Next
The main issue is that, when you loop through the range, each cell
refers to a particular cells on the sheet.主要问题是,当您遍历范围时,每个
cell
都引用工作表上的特定单元格。
So your loop loops through I2, I3, I4, ...
.因此,您的循环遍历
I2, I3, I4, ...
If you delete a row, all the other rows are moved up, and what was in cell Ix
is now in cell I(x-1)
, but the loop will be at cell Ix
, and so a whole row will have avoided being processed.如果删除一行,所有其他行都会向上移动,单元格
Ix
中的内容现在位于单元格I(x-1)
中,但循环将在单元格Ix
处,因此整行将避免被处理.
One solution is to store all the rows that are to be deleted in a Collection
, and then delete the collection afterwards.一种解决方案是将所有要删除的行存储在
Collection
中,然后删除该集合。
'data
Cells.Clear
For i = 1 To 15
Cells(i, 1) = Int(Rnd * 4)
Cells(1, i + 2) = Cells(i, 1)
Next i
'code
Dim tbd As New Collection 'to be deleted collection
For Each c In [a1:a15]
If c = 1 Then tbd.Add c 'adds a row that is to be deleted
Next c
For Each c In tbd
c.Delete 'deletes all rows in tbd
Next c
The first part of the code creates some sample data to process.代码的第一部分创建一些要处理的示例数据。 Then it defines a new
Collection
, adds the rows to it that are to be deleted (anything with a value 1 is this case), and then deletes them from the collection.然后它定义一个新的
Collection
,将要删除的行添加到其中(在这种情况下值为 1 的任何行),然后从集合中删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.