【问题标题】:vba scan Col & Delete if 0 and then insert row if not equal to next rowvba扫描列如果为0则删除,如果不等于下一行则插入行
【发布时间】:2016-01-02 15:39:33
【问题描述】:

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

代码似乎可以运行并执行我需要的操作,如果有 0 值,则扫描 Co B 并删除,如果下面的行不同,则扫描 Col I 并插入行,然后对 Col H 重复。但是我得到一个“运行时1004 application-defined or object defined error”消息而不是刚刚结束的宏。接受任何修改或建议

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 

【问题讨论】:

    标签: vba excel if-statement runtime-error


    【解决方案1】:
    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
    

    应该做的伎俩。

    【讨论】:

    • 向前循环会花费更长的时间,因为它们正在插入行;)此外,当您使用他们现有的代码时,人们通常倾向于更轻松地处理事情。话虽如此,我刚刚在等式中引入了一个立即如果 >.
    • 另外,在下一次运行 H 列时,他会为通过 J 列时添加的每一行添加两行。当 lrow 的数据不等于上面的空行时,一行再次将空行与上面的数据进行比较。
    • @macroman 效果很好。从上到下运行这个有什么好处。我发现 IF 语句在进行谷歌搜索,它恰好在我使用的另一个宏中工作。
    • 额外插入的行很好。它有助于直观地描绘主要组与子组的中断。
    • IIf()If...Then... 非常 不同,但谷歌上有很多解释 - 请注意仅此而已。每当您插入/删除行时,您应该始终从下到上,因为您在变量达到该数字之前添加/删除行号。这将不可避免地导致问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多