vba scan Col&如果为0则删除,然后如果不等于下一行则插入行

时间:2015-10-05 20:59:24

标签: vba excel-vba if-statement runtime-error excel

这就是我的数据。它是另一张纸的摘要。

代码似乎运行并执行我需要的操作,扫描Co B并删除是否有0值,扫描Col I并插入行,如果下面的行不同,则重复Col H.但是我得到一个“运行时” 1004应用程序定义的或对象定义的错误“消息而不是刚刚结束的宏。可以打开任何编辑或建议

Range("A100000").End(xlUp).Activate
Range("N1") = ActiveCell.Row

For lRow = Cells(Cells.Rows.Count, "b").End(xlUp).Row To 1 Step -1    
    If Cells(lRow, "b") = 0 Then
        Rows(lRow).EntireRow.Delete                            
    End If
Next lRow

For lRow = Cells(Cells.Rows.Count, "I").End(xlUp).Row To 1 Step -1    
    If Cells(lRow, "I") <> Cells(lRow - 1, "I") Then '<~~ debugger highlights this line or the other version of this eq below
            Rows(lRow).EntireRow.Insert    
    End If
Next lRow

For lRow = Cells(Cells.Rows.Count, "H").End(xlUp).Row To 1 Step -1    
    If Cells(lRow, "H") <> Cells(lRow - 1, "H") Then
        Rows(lRow).EntireRow.Insert                
    End If
Next lRow

Range("A1").Activate

Application.ScreenUpdating = True

End Sub 

1 个答案:

答案 0 :(得分:3)

If Cells(lRow, "I") <> Cells(lRow - 1, "I") Then

lRow不可避免地达到1的值时,这会导致错误,因为

lRow - 1

0 - 并且没有行号0。

您需要为此可能性编码:

For lRow = Cells(Cells.Rows.Count, "I").End(xlUp).Row To 1 Step -1    
    If Cells(lRow, "I") <> Cells(lRow - IIf(lRow = 1, 0, 1), "I") Then
            Rows(lRow).EntireRow.Insert    
    End If
Next lRow

应该做的伎俩。