如何用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 & ")" 

我相信你会注意到总结在最后一行之后,是整列。

谢谢你的帮助

你没有提到什么样的公式,你可能想把公式添加到我刚刚添加的三行中,所以我留在一个占位符中。

 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 

也没有提及寻找并可能删除以前可能已经遗留下来的列的底部的总和公式,但是我想这是每次都要对原始数据执行的。