以下是一个基本的VBA代码实现:

Sub SummarizeData() Dim wb As Workbook Dim ws As Worksheet Dim rng As Range Dim dict As Object Dim key As Variant Dim i As Integer Dim lastRow As Long

'设置工作簿和工作表
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")

'获取数据范围
lastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
Set rng = ws.Range("B2:F" & lastRow)

'初始化字典对象
Set dict = CreateObject("Scripting.Dictionary")

'遍历数据范围,将相同的bcde进行f列数据汇总
For i = 1 To rng.Rows.Count
    key = rng.Cells(i, 1).Value & "_" & rng.Cells(i, 2).Value & "_" & rng.Cells(i, 3).Value & "_" & rng.Cells(i, 4).Value
    If dict.Exists(key) Then
        dict(key) = dict(key) + rng.Cells(i, 5).Value
    Else
        dict(key) = rng.Cells(i, 5).Value
    End If
Next i

'新建工作簿和工作表
Set newWb = Workbooks.Add
Set newWs = newWb.Sheets("Sheet1")

'将分类汇总结果放在新工作表sheet1中,bcde放条件,f列为汇总结果
newWs.Cells(1, 1).Value = "B"
newWs.Cells(1, 2).Value = "C"
newWs.Cells(1, 3).Value = "D"
newWs.Cells(1, 4).Value = "E"
newWs.Cells(1, 5).Value = "F"
i = 2
For Each key In dict.keys
    newWs.Cells(i, 1).Value = Split(key, "_")(0)
    newWs.Cells(i, 2).Value = Split(key, "_")(1)
    newWs.Cells(i, 3).Value = Split(key, "_")(2)
    newWs.Cells(i, 4).Value = Split(key, "_")(3)
    newWs.Cells(i, 5).Value = dict(key)
    i = i + 1
Next key

'自适应列宽
newWs.Cells.EntireColumn.AutoFit

'释放对象
Set dict = Nothing
Set rng = Nothing
Set ws = Nothing
Set newWs = Nothing
Set newWb = Nothing

End Sub

请根据实际情况进行调整。


原文地址: https://www.cveoy.top/t/topic/96S 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录