使用VBA代码合并重复行并求和如果您对VBA代码感兴趣,在本节中,我们将提供一段VBA代码来合并重复行并对其他列中的对应值进行求和。请按照以下步骤操作:
步骤 1:打开VBA模块编辑器并复制代码
在Excel中按住“ALT + F11”键以打开“Microsoft Visual Basic for Applications”窗口。 点击“插入”>“模块”,并将以下代码粘贴到“模块”窗口中。VBA代码:合并重复行并求和 Sub CombineDuplicateRowsAndSumForMultipleColumns()
'Update by Extendoffice
Dim SourceRange As Range, OutputRange As Range
Dim Dict As Object
Dim DataArray As Variant
Dim i As Long, j As Long
Dim Key As Variant
Dim ColCount As Long
Dim SumArray() As Variant
Dim xArr As Variant
Set SourceRange = Application.InputBox("Select the original range:", "Kutools for Excel", Type:=8)
If SourceRange Is Nothing Then Exit Sub
ColCount = SourceRange.Columns.Count
Set OutputRange = Application.InputBox("Select a cell for output:", "Kutools for Excel", Type:=8)
If OutputRange Is Nothing Then Exit Sub
Set Dict = CreateObject("Scripting.Dictionary")
DataArray = SourceRange.Value
For i = 1 To UBound(DataArray, 1)
Key = DataArray(i, 1)
If Not Dict.Exists(Key) Then
ReDim SumArray(1 To ColCount - 1)
For j = 2 To ColCount
SumArray(j - 1) = DataArray(i, j)
Next j
Dict.Add Key, SumArray
Else
xArr = Dict(Key)
For j = 2 To ColCount
xArr(j - 1) = xArr(j - 1) + DataArray(i, j)
Next j
Dict(Key) = xArr
End If
Next i
OutputRange.Resize(Dict.Count, ColCount).ClearContents
i = 1
For Each Key In Dict.Keys
OutputRange.Cells(i, 1).Value = Key
For j = 1 To ColCount - 1
OutputRange.Cells(i, j + 1).Value = Dict(Key)(j)
Next j
i = i + 1
Next Key
Set Dict = Nothing
Set SourceRange = Nothing
Set OutputRange = Nothing
End Sub
步骤 2:执行代码
粘贴此代码后,请按“F5”键运行此代码。在弹出的对话框中,选择您希望合并和求和的数据范围。然后,点击“确定”。 在下一个弹出对话框中,选择一个单元格作为输出结果的位置,然后点击“确定”。 结果:
现在,重复行已合并,并且其对应的值已求和。如下图所示: