如何在excel中“合并/分组”,并在excel中添加不同列上的值

ID Name Valued 1 John 1.23 2 Eve 2.20 1 John 2.30 3 Adam 4.50 3 Eve 2.00 and so on... 

我想要这样的结果

 ID Name Valued 1 John 3.33 "valued were sum from rows 1 & 2 - because they have the same ID" 2 Eve 2.20 3 Adam 6.50 "valued were sum from 4 & 5 - because they have the same ID whatever the data under the column Name" 

我怎样才能使用VBA for Excel编写这个?

查看Excel中的SUMIF()函数 – https://support.office.com/zh-cn/article/SUMIF-function-169b8c99-c05c-4483-a712-1697a653039b

它正是你所需要的。 在你的情况下,这些是公式:

 =SUMIF(C:C,1) =SUMIF(C:C,2) =SUMIF(C:C,3) 

假设:应该在结果中显示名称首先出现的具有多个名称的唯一ID。

解决scheme1:使用VBA

考虑到你的数据在Column AC以下将在Column EG显示结果

 Sub Demo() Dim ws As Worksheet Dim dataRng As Range Dim dic1 As Variant, dic2 As Variant, arr As Variant Dim cnt As Long Set ws = ThisWorkbook.Sheets("Sheet1") 'change Sheet1 to your data sheet Set dic1 = CreateObject("Scripting.Dictionary") Set dic2 = CreateObject("Scripting.Dictionary") Application.ScreenUpdating = False With ws lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'get last row in Column A Set dataRng = .Range("A2:C" & lastRow) 'range of data Column AC arr = dataRng.Value 'range to array For i = 1 To UBound(arr) 'loop through each row dic1(arr(i, 1)) = dic1(arr(i, 1)) + arr(i, 3) 'add values of unique id If dic2.exists(arr(i, 1)) = False Then dic2(arr(i, 1)) = arr(i, 2) 'first name for unique id End If Next .Range("E2").Resize(dic1.Count, 1) = Application.WorksheetFunction.Transpose(dic1.keys) 'uniques id in Column E .Range("G2").Resize(dic1.Count, 1) = Application.WorksheetFunction.Transpose(dic1.items) 'names in Column E .Range("F2").Resize(dic2.Count, 1) = Application.WorksheetFunction.Transpose(dic2.items) 'sum of values in Column E End With Application.ScreenUpdating = True End Sub 

看图像以供参考。

在这里输入图像说明

解决scheme2:使用公式

要获得Unique ID ,请在Cell E2input以下公式

 =IFERROR(INDEX($A$2:$A$6,MATCH(0,INDEX(COUNTIF(E$1:$E1,$A$2:$A$6),0,0),0)),"") 

Cell F2input下面的公式,得到第一个出现的对应的ID为Name

 =INDEX($B$2:$B$6,MATCH(E2,$A$2:$A$6,0)) 

最后得到Sum of Values ,在Cell G2input以下公式

 =SUMIF($A$2:$A$6,E2,$C$2:$C$6) 

按需要拖放/复制所有公式,并根据您的数据更改范围。

在这里输入图像说明