VBA代码:合并重复的行并求和Sub CombineRows() 'Updateby Extendoffice Dim WorkRng As Range Dim Dic As Variant Dim arr As Variant On Error Resume Next xTitleId = "KutoolsforExcel" Set WorkRng = Application.Selection Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8) Set Dic = CreateObject("Scripting.Dictionary") arr = WorkRng.Value For i = 1 To UBound(arr, 1) Dic(arr(i, 1)) = Dic(arr(i, 1)) + arr(i, 2) Next Application.ScreenUpdating = False WorkRng.ClearContents WorkRng.Range("A1").Resize(Dic.Count, 1) = Application.WorksheetFunction.Transpose(Dic.keys) WorkRng.Range("B1").Resize(Dic.Count, 1) = Application.WorksheetFunction.Transpose(Dic.items) Application.ScreenUpdating = True End Sub
3。 然后按F5键以运行此代码,并且需要在弹出的提示框中选择要合并的范围。 看截图:
4。 然后点击OK,重复的行已合并,并将值相加。
备注:如果要使用此代码,则最好制作一个文件副本以避免破坏数据,并且此代码仅适用于两列。