在更改行值后,在另一列中执行一个加总行

我希望你能帮助我的VBA问题。 我想使用一个循环往下列A.一旦检测到一个变化,我想在列C中插入一个SUMIF公式,如果分组的列A(总偏移到右边)。 A已经sorting。 有点像小计,但没有使用小计行。

ABC
1 2
1 6
1 3 11 = SUMIF(A:A,A3,B:B)

2 7
2 8 15 = SUMIF(A:A,A5,B:B)

3 8
3 6 14 = SUMIF(A:A,A7,B:B)

(没有添加1和2和2和3变化之间的空白行)我相信我是以下代码片段的方式的一部分,但是一起工作有麻烦。

Sub SUMIF_Upon_Change() Dim r As Long, mcol As String, i As Long ' find last used cell in Column A r = Cells(Rows.Count, "A").End(xlUp).Row ' get value of last used cell in column A mcol = Cells(r, 1).Value ' insert rows by looping from bottom For i = r To 2 Step -1 If Cells(i, 1).Value <> mcol Then Cells(n, 3).Formula = _ "=SUMIF(A:A,RC[-1],B:B)" 'AND / OR This added at the change row minus one row. 'Places formula in each adjacent cell (in column "D"). Range("C2:C" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=SUMIF(A:A,A3,BB)" End If Next i End Sub 

任何帮助都感激不尽。

XLMatters,你几乎有它。 你唯一的主要问题是你似乎混合公式参考样式(“RC [-1]”和“A3”)。 你必须select一个或另一个。 以下是您的代码的一个工作示例,只需进行一些小修改:

 Sub SUMIF_Upon_Change() Dim r As Long, mcol As String, i As Long ' find last used cell in Column A r = Cells(Rows.Count, "A").End(xlUp).Row ' get value of last used cell in column A mcol = Cells(r, 1).Value For i = r To 2 Step -1 If Cells(i, 1).Value <> Cells(i + 1, 1).Value Then Cells(i, 3).Formula = "=SUMIF(A:A,A" & i & ",B:B)" End If Next i End Sub 

如果你的心是在FormulaR1C1风格上设置的,你可以这样:

 Sub SUMIF_Upon_ChangeRC() Dim r As Long, mcol As String, i As Long ' find last used cell in Column A r = Cells(Rows.Count, "A").End(xlUp).Row ' get value of last used cell in column A mcol = Cells(r, 1).Value For i = r To 2 Step -1 If Cells(i, 1).Value <> Cells(i + 1, 1).Value Then Cells(i, 3).FormulaR1C1 = "=SUMIF(C1,RC1,C2)" End If Next i End Sub 

如果您有任何其他问题,请询问。