excel - 查找 A 列中的更改并使用 Excel VBA 插入 4 行

标签 excel insert vba

我试图让我的代码每次在下面的单元格中发现差异时插入四行。如果 A5-55 = 1、A56-80 = 2、A81 - 100 = 3 我希望代码看到 56 不等于 55 并插入 4 行,然后继续沿着 A 列向下移动,直到没有更多值。

我不断收到 Excel 错误,

can not complete task. Resources error

然后 range 类的运行时 1004 插入方法失败,调试器突出显示插入行的代码

Enter image description here

Enter image description here

这就是我的数据:

Enter image description here

Worksheets("HR-Calc").Activate
For lRow = Cells(Cells.Rows.Count, "A").End(xlUp).Row To 6 Step -1

If Cells(lRow, "A") <> Cells(lRow - 1, "A") Then
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
End If
Next lRow

最佳答案

更简洁的方法是在 table 上使用自动过滤器

(代码假设 A 列是一个排序的整数 ID - 正如图像中的情况)

Sub InsertRowsBetweenIncrements()

    Dim ws As Worksheet: Set ws = Worksheets("HR-Calc")
    Dim HeaderRow As Long: HeaderRow = 4

    Application.ScreenUpdating = False

        Dim LastRow As Long: LastRow = ws.Columns(1).Find("*", _
            SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        Dim LastCol As Long: LastCol = ws.Cells.Find("*", _
            SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        Dim Tbl As Range: Set Tbl = ws.Range(Cells(HeaderRow, 1), Cells(LastRow, LastCol))
        Dim i As Long, j As Long

        For i = ws.Cells(LastRow, 1).Value To 1 Step -1
            Tbl.AutoFilter Field:=1, Criteria1:=i
            j = Tbl.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeLastCell).Row
            Tbl.AutoFilter
            If j <> HeaderRow And j < LastRow Then _
                ws.Rows(j + 1 & ":" & j + 4).Insert Shift:=xlDown
        Next i

    Application.ScreenUpdating = True

End Sub

关于excel - 查找 A 列中的更改并使用 Excel VBA 插入 4 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32870865/

相关文章:

Excel 2010 VBA 绘制图表宏

excel - 压缩两个和的差的公式

sql - 表 A 引用表 B,我如何插入(使用 Perl 和 DBI 以及 PostgreSQL)

java - 通过 hibernate 插入数据库

excel - 我如何循环遍历数组的数组

vba - 设置 PivotItem.Visible = false 时无法设置 PivotItem 类的 Visible 属性

VBA:尝试访问网站,但网站偶尔无法加载

即使编码了密码后,Excel VBA 仍然提示输入密码

sql - 回车 Oracle 10g SQL

java - 插入的条目不会永久保留在数据库中