如何使用VBA插入行,然后在其中编写公式?

时间:2015-07-22 21:11:35

标签: excel vba

我不相信这已经被问过或者已经提出了类似的问题。我试图根据列中的值分隔我的数据集。然后我想在它们之间插入3行。最后,我想在我刚刚添加的三个中间行添加公式。我的弗兰肯斯坦的代码(由其他人组成的部分)是:

Dim LastRow As Long
Dim i As Long

LastRow = Cells(Rows.Count, "AA").End(xlUp).Row

For i = LastRow To 2 Step -1
    If i = 2 Then
        'Do nothing
    ElseIf Cells(i, "AA") <> Cells(i - 1, "AA") Then
        Rows(i).Select
        Selection.Insert Shift:=xlDown
        Selection.Insert Shift:=xlDown
        Selection.Insert Shift:=xlDown
    End If
Next i

LR = Range("AA" & Rows.Count).End(xlUp).Row
Range("AA1:AA" & LR & "").Interior.Color = RGB(217, 217, 217)
Range("AA" & LR + 2).Formula = "=SUM(Z2:Z" & LR & ")"

我确信您会注意到总和位于最后一行之后,并且是整列。

感谢您提供任何帮助

1 个答案:

答案 0 :(得分:0)

您还没有提到您希望将公式添加到我刚刚添加的三个中间行中的公式。所以我已经离开了占位符。

Dim LastRow As Long, i As Long, lr As Long

With Sheets("Sheet5")   'set this worksheet reference properly!
    LastRow = .Cells(Rows.Count, "AA").End(xlUp).Row

    For i = LastRow To 3 Step -1
        If .Cells(i, "AA").Value <> .Cells(i - 1, "AA").Value Then
            .Cells(i, "AA").Resize(3, 1).EntireRow.Insert
            .Cells(i + 1, "AA").Formula = "=SUM(AA2:AA" & i & ")"
        End If
    Next i

    lr = .Range("AA" & Rows.Count).End(xlUp).Row
    .Range("AA1:AA" & lr).Interior.Color = RGB(217, 217, 217)
    .Range("AA" & lr + 2).Formula = "=SUM(Z2:Z" & lr & ")"
End With

也没有提到在列的底部寻找并可能删除以前的总和公式,这些公式可能是从之前的运行中留下的,但我认为这将在每个原始数据上执行时间。