通过分析值在Excel中插入行

时间:2014-08-11 14:37:58

标签: excel excel-vba insert row vba

我有一个包含数字和文字的巨大电子表格。 第一列看起来像这样:

1111
1111
2222
2222
2222
3333
3333
3333

我想在新的唯一编号开头的地方插入一个空白行。即当我在111之后开始222222时,我想插入一个空行。

2 个答案:

答案 0 :(得分:0)

这就是你要找的。

Sub InsertRows()
Dim i, RowVal1, RowVal2
i = 1
Do
RowVal1 = Worksheets("Sheet1").Cells(i, 1).Value
RowVal2 = Worksheets("Sheet1").Cells(i + 1, 1).Value
If RowVal1 <> RowVal2 Then
Worksheets("Sheet1").Cells(i + 1, 1).EntireRow.Insert
i = i + 1
End If
i = i + 1
Loop While (RowVal2 <> "")
End Sub

答案 1 :(得分:0)

这种问题经常出现,我希望VBA允许更高阶的功能,所以Insert只能替换为委托。

Sub SeparateByID(ByRef rng as Range, ByVal id_col as Variant)

    Dim row_count as Integer
    row_count = rng.Rows.Count

    Dim last_id As Variant
    last_id = rng.cells(row_count , id_col).value

    Dim row_index as Integer
    For row_index = row_count To 1 Step -1

        Dim crnt_id As Variant
        crnt_id = rng.cells(row_index, id_col).value

        If last_id <> crnt_id Then 

            rng.cells(row_index + 1, id_col).EntireRow.Insert shift:=xlDown
            last_id = crnt_id 

        End If

    Next row_index 

End Sub

注意:应该事先对范围进行排序。

有些人试图实施代表......

Sub InsertNewRow(rng as Range)

    rng.EntireRow.Insert shift:=xlDown

End Sub

Sub DoBetweenIDs(ByRef rng as Range, ByVal id_col as Variant, ByVal delegate As String)

    Dim row_count as Integer
    row_count = rng.Rows.Count

    Dim last_id As Variant
    last_id = rng.cells(row_count , id_col).value

    Dim row_index as Integer
    For row_index = row_count To 1 Step -1

        Dim crnt_id As Variant
        crnt_id = rng.cells(row_index, id_col).value

        If last_id <> crnt_id Then 

            Application.Run delegate, rng.cells(row_index + 1, id_col)
            last_id = crnt_id

        End If

    Next row_index 

End Sub