如何使用excel vba进行合并和求和

时间:2018-04-17 04:36:45

标签: excel vba excel-vba excel-2007

我试图创建vba来合并文本值并将金额相加。 例如,我有以下数据

Date         Name            Type       Amount
1 Jan        Test1            A           100
1 Jan        Test1            A           150
2 Jan        Test1            A           110
2 Jan        Test1            A           200
1 Jan        Test1            B           130
1 Jan        Test1            B           110
1 Jan        Test2            B           130
1 Jan        Test2            B           160
1 Jan        Test3            B           180

结果应如下所示

Date         Name            Type       Amount
1 Jan        Test1            A           250
2 Jan        Test1            A           310
1 Jan        Test1            B           240
1 Jan        Test2            B           290
1 Jan        Test3            B           180

我尝试使用以下vba,但似乎不起作用 How to SUM / merge similar rows in Excel using VBA?

1 个答案:

答案 0 :(得分:0)

以下内容如何,​​通过使用SumIf公式然后替换D列中的值并删除重复项,这将为您提供所需的结果:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A

ws.Range("E2").FormulaR1C1 = "=SUMIFS(C[-1],C[-4],RC[-4],C[-3],RC[-3],C[-2],RC[-2])"
'add the sumif formula
ws.Range("E2").AutoFill Destination:=Range("E2:E" & LastRow), Type:=xlFillDefault
'fill the formula down to last cell
ws.Columns("E:E").Copy
ws.Columns("E:E").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
'copy and paste as values
ws.Range("D2:D" & LastRow).Delete Shift:=xlToLeft
'remove column D's values and bring values from Column E into it
ws.Range("$A$1:$G$" & LastRow).RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7), Header:=xlNo
'remove duplicates
End Sub