Excel VBA – 添加行并激活

晚上好

有关我的数据的示例,请参阅附加的图像。 列A中的string被分组在一起。

在这里输入图像说明

下面的代码是一个WIP实现以下…

  1. 查找每个交付地点的最后一次出现,然后添加一个新行。
  2. 在新创build的行中,在名为Header11-14的列中,添加一个公式来合计上述行中的值
  3. 做一些格式化

到目前为止,它增加了每个交货地点后的新行,但我不明白是如何添加总和公式。 我知道如何添加string,但我不知道如何引用上面的单元格…

在这里输入图像说明

上面的图片,我试图实现。

Sub insertRow_totals() Dim changeRow, counter As Integer counter = 2 While Cells(counter, 1) <> "" If Cells(counter, 1) <> Cells(counter - 1, 1) Then Rows(counter).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove counter = counter + 2 End If counter = counter + 1 Wend Rows(2).EntireRow.Delete End Sub 

你需要计算有多less行同名(或记住第一个行的索引),然后像这样的东西应该工作

 Sub insertRow_totals() Dim changeRow, counter As Integer counter = 2 FirstRow = 2 While Cells(counter, 1) <> "" If Cells(counter, 1) <> Cells(counter - 1, 1) Then Rows(counter).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove For i = 11 To 14 ActiveSheet.Cells(counter, i).Formula = "=SUM(" & Cells(FirstRow, i).Address & ":" & Cells(counter - 1, i).Address & ")" Next i counter = counter + 1 FirstRow = counter End If counter = counter + 1 Wend Rows(2).EntireRow.Delete End Sub