首页 > 解决方案 > 如何使用 VBA 在列中插入组上方/下方的行

问题描述

我什至为此启动宏都遇到了麻烦。任何帮助将不胜感激。

参考下面的示例,是否可以找到组的第一个值并在其上方插入一行。如:在A列中找到第一个“苹果”并在上方插入行,在A列中找到第一个“香蕉”并在上方插入行等。查找组中的最后一个值并在下方插入行也可以,如:在A列中找到最后一个“苹果”并在下面插入行。

还需要的是,如果 A 列中没有“苹果”,则转到“香蕉”。

 	  A
1	apple
2	apple
3	apple
4	apple
5	banana
6	banana
7	banana
8	banana
9	banana
10	orange
11	orange
12	orange
13	orange
14	orange
15	orange

标签: excelvba

解决方案


这是一个应该做你正在寻找的子程序。

Sub main()
    Dim lastRow As Long
    Dim firstFruit As String

    With Sheets("Sheet1")
        'find last row containing a value
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        'initialize our first fruit as the first cell with a value.
        firstFruit = .Cells(1, 1).Value

        For ctr = 1 To lastRow
            If (.Cells(ctr, 1).Value <> firstFruit) Then 'we've found a new fruit
                .Rows(ctr & ":" & ctr).Insert 'insert our row above where we found it
                firstFruit = .Cells(ctr + 1, 1).Value 'set our fistFruit to equal the value of the new fruit
                lastRow = lastRow + 1 'add +1 to lastRow because we've added a new one
            End If
        Next ctr
    End With
End Sub

推荐阅读