vba 如何根据ABC列是否相同,相同进行汇总对P到AC列的值求和,其他列默认找到的第一个,结果写入sheet2
时间: 2024-02-09 19:11:46 浏览: 32
您可以使用VBA中的Dictionary对象来解决这个问题。具体步骤如下:
1. 定义一个Dictionary对象,用于存储每个ABC列相同的行的数据。
2. 使用For循环遍历每一行数据,以ABC列的值为key,将找到的行数据添加为value。
3. 对于每个key对应的value,进行P到AC列的值求和,并将结果写入sheet2中。
下面是示例代码,您可以根据自己的需求进行修改:
```
Sub SumByABC()
Dim dict As New Dictionary
Dim lastRow As Long, i As Long
Dim key As String, value As Variant
Dim sumP As Double, sumQ As Double, sumR As Double
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastRow
key = Cells(i, 1).Value & Cells(i, 2).Value & Cells(i, 3).Value
value = Array(Cells(i, 1).Value, Cells(i, 2).Value, Cells(i, 3).Value, _
Cells(i, 16).Value, Cells(i, 17).Value, Cells(i, 18).Value)
If dict.Exists(key) Then
dict.Item(key) = Array(dict.Item(key), value)
Else
dict.Add key, value
End If
Next i
For Each key In dict.keys
sumP = 0: sumQ = 0: sumR = 0
For i = LBound(dict.Item(key), 1) To UBound(dict.Item(key), 1)
sumP = sumP + dict.Item(key)(i, 4)
sumQ = sumQ + dict.Item(key)(i, 5)
sumR = sumR + dict.Item(key)(i, 6)
Next i
Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Resize(1, 6).Value = _
Array(dict.Item(key)(1, 1), dict.Item(key)(1, 2), dict.Item(key)(1, 3), sumP, sumQ, sumR)
Next key
End Sub
```
注意,在使用该代码之前,需要先添加对Microsoft Scripting Runtime的引用。方法为:在VBA编辑器中,依次选择“工具”-“引用”,然后勾选“Microsoft Scripting Runtime”。