我将以下表格作为示例: Example of how the sheet can look 我需要一种搜索整个A列的语言,当它找到同一帐户的副本(如167)时,它会将所有帐户值(来自D和E)与F列中的相同帐号(对于D列)和G相加(对于E栏)。如果总和可以在重复的最后一个帐户的最后一个单元格中找到,那将是很好的。在167的情况下,这意味着F / G10。
P.S。如果我在将它们相加之后也删除前面的行(仅保留最后一行的总和),我该怎么做?
谢谢!很棒的答案!
答案 0 :(得分:1)
对于公式解决方案:
将其放入单元格F2
并填写:
=IF(COUNTIF(A3:$A$17,A2)>0,"",SUMIF(A:A,A2,D:D))
将其放入单元格G2
并填写:
=IF(COUNTIF(A3:$A$17,A2)>0,"",SUMIF(A:A,A2,E:E))
假设您的数据集超过了屏幕截图,您需要更改$A$17
中的COUNTIF
以匹配最后一行数据之后的行。
对于VBA解决方案:
这将为您进行计算,并仅填充结果的值:
Sub test()
Dim i As Integer
Dim lRow As Integer
Dim j As String
lRow = Cells(Rows.Count, "A").End(xlUp).Row
With ThisWorkbook.ActiveSheet
For i = 2 To lRow
j = .Evaluate("=IF(COUNTIF(A" & i + 1 & ":$A$" & lRow + 1 & ",A" & i & ")>0,"""",SUMIF(A:A,A" & i & ",D:D))")
.Cells(i, 6).Value = j
Next i
For i = 2 To lRow
j = .Evaluate("=IF(COUNTIF(A" & i + 1 & ":$A$" & lRow + 1 & ",A" & i & ")>0,"""",SUMIF(A:A,A" & i & ",E:E))")
.Cells(i, 7).Value = j
Next i
End With
End Sub
这会将公式粘贴到各自的单元格中,但会将公式保留在那里:
Sub test()
Dim i As Integer
Dim lRow As Integer
lRow = Cells(Rows.Count, "A").End(xlUp).Row
With ThisWorkbook.ActiveSheet
For i = 2 To lRow
.Cells(i, 6).Value = "=IF(COUNTIF(A" & i + 1 & ":$A$" & lRow + 1 & ",A" & i & ")>0,"""",SUMIF(A:A,A" & i & ",D:D))"
Next i
For i = 2 To lRow
.Cells(i, 7).Value = "=IF(COUNTIF(A" & i + 1 & ":$A$" & lRow + 1 & ",A" & i & ")>0,"""",SUMIF(A:A,A" & i & ",E:E))"
Next i
End With
End Sub
答案 1 :(得分:0)
替代VBA解决方案
使用公式
Sub Test_KeepFormulas()
ThisWorkbook.ActiveSheet.Columns("A").SpecialCells(xlCellTypeConstants, xlNumbers).Offset(, 5).Resize(, 2).FormulaR1C1 = "=IF(COUNTIF(R[+1]C1:R20C1, RC1)>0,"""",SUMIF(C1,RC1,C[-2]))"
End Sub
带值
Sub Test_KeepValues()
With ThisWorkbook.ActiveSheet.Columns("A").SpecialCells(xlCellTypeConstants, xlNumbers).Offset(, 5).Resize(, 2)
.FormulaR1C1 = "=IF(COUNTIF(R[+1]C1:R20C1, RC1)>0,"""",SUMIF(C1,RC1,C[-2]))"
.Value = .Value
End With
End Sub