Excel VBA – 需要循环删除整行上面的行,其中单元格值<> 0

好的,所以我有一张Excel格式的表格,这个格式对于我的目的来说是很糟糕的,我每天都在做这个表格。 数据默认以下列格式列出(如在Excel表格中查看):

x1,y1,z1,i1 , ,z2,i2 , ,z3,i3 ****Blank row**** ****Blank row**** ****Blank row**** x2,y2,z4,i4, , ,z5,i5, , ,z6,i6, ^above would represent the last row for demontration purposes, but the real sheet extends up 1000s of rows 

为了以更友好的格式获取数据,我需要一个循环,从最后一行(erow)一直到第3行(数据开始的地方)。 当它发现第2列中的行是<>到“”时,我想要它删除该单元格上面的整个3行,所以最终目标是将数据格式化(如在Excel表格中查看):

 x1,y1,z1,i1 , ,z2,i2 , ,z3,i3 x2,y2,z4,i4 , ,z5,i5 , ,z6,i6 

以下是我到目前为止。 当然,它根本不起作用,否则我不会在这里。 它正在删除所有的数据,直到第3行,我不明白为什么。 任何想法将不胜感激。

 Sub test() Dim currentSht As Worksheet Dim erow Dim i As Integer Set currentSht = ActiveWorkbook.Sheets(1) erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row For i = erow To 3 Step -3 If currentSht.Cells(i, 1).Value <> " " Then currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete End If Next i End Sub 

这是因为你不断testing同一行,并删除上面的3行。

比方说, i是30,它parsing为真,因为在第2列有数据。我们删除它上面的三行,使当前行,第27行,然后i迭代-3, i是27,它testing相同的数据对于相同的数据它又解决了。

所以我们需要强制i改变行号:

 Sub test() Dim currentSht As Worksheet Dim erow Dim i As Integer Set currentSht = ActiveWorkbook.Sheets(1) erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row For i = erow To 3 Step -1 If Trim(currentSht.Cells(i, 1).Value) <> "" Then currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete i = i - 3 End If Next i 

尝试颠倒IF

 Sub test() Dim currentSht As Worksheet Dim erow Dim i As Integer Set currentSht = ActiveWorkbook.Sheets(1) erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row For i = erow To 3 Step -3 If currentSht.Cells(i, 1).Value = "" Then currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete End If Next i End Sub