vba扫描列如果为0则删除,如果不等于下一行则插入行

标签 vba excel if-statement runtime-error

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

代码似乎可以运行并执行我需要的操作,如果有 0 值,则扫描 Co B 并删除,如果下面的行不同,则扫描 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 

最佳答案

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

应该做的伎俩。

关于vba扫描列如果为0则删除,如果不等于下一行则插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957797/

相关文章:

excel - 我怎样才能在VBA中简化这个表达式

Excel 数据验证以另一个单元格值为条件

vba - 如果甚至没有一个单元格是红色或蓝色,则删除整行

javascript - 在 IE 7 中使用 JavaScript 将 Base64 字符串保存为 Excel .xls 文件

c++ - stm32时序ULPI接口(interface)

linux - 如何使用带有路径字符串的现有语句?

vba - 查找具有特定颜色的范围内的单元格并添加注释

excel - 将多个不连续范围合并到一个命名范围中以清理公式

SQL Server BCP 实用程序

javascript - For循环是否在预期> 1时返回1 for count