写一个vba代码,目的是将工作表1的重复数据加总然后放入工作表2
时间: 2023-05-20 22:03:07 浏览: 48
非常感谢您的提问。以下是一个简单的 VBA 代码,可以将工作表1中的重复数据加总并放入工作表2:
Sub SumDuplicates()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow As Long, i As Long
Dim dict As Object
Dim key As Variant
Set ws1 = ThisWorkbook.Worksheets("工作表1")
Set ws2 = ThisWorkbook.Worksheets("工作表2")
lastRow = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
Set dict = CreateObject("Scripting.Dictionary")
For i = 2 To lastRow
If Not dict.Exists(ws1.Cells(i, 1).Value) Then
dict.Add ws1.Cells(i, 1).Value, ws1.Cells(i, 2).Value
Else
dict(ws1.Cells(i, 1).Value) = dict(ws1.Cells(i, 1).Value) + ws1.Cells(i, 2).Value
End If
Next i
i = 2
For Each key In dict.Keys
ws2.Cells(i, 1).Value = key
ws2.Cells(i, 2).Value = dict(key)
i = i + 1
Next key
Set dict = Nothing
End Sub
希望这个代码能够帮到您。如果您有任何其他问题,请随时问我。