以下是VBA代码实现:

Sub SummarizeData() Dim ws As Worksheet Set ws = Worksheets("Sheet1") '修改为实际工作表名

'定义变量
Dim lastRow As Long
Dim bcdeCol As Long
Dim fCol As Long
Dim bcde As String
Dim fValue As Double
Dim summaryDictionary As Object '使用字典对象存储分类汇总结果

'初始化变量
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
bcdeCol = 2 '修改为实际bcde列的列号
fCol = 6 '修改为实际f列的列号
Set summaryDictionary = CreateObject("Scripting.Dictionary")

'循环遍历数据
For i = 2 To lastRow '从第2行开始,第1行为表头
    bcde = ws.Cells(i, bcdeCol).Value
    fValue = ws.Cells(i, fCol).Value
    
    '判断字典中是否已存在该分类
    If summaryDictionary.exists(bcde) Then
        '如果已存在,则累加该分类的汇总值
        summaryDictionary(bcde) = summaryDictionary(bcde) + fValue
    Else
        '如果不存在,则添加该分类及汇总值
        summaryDictionary.Add bcde, fValue
    End If
Next i

'新建工作簿,将分类汇总结果写入新工作表Sheet1中
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add '新建工作簿
Dim newWs As Worksheet
Set newWs = newWorkbook.Sheets("Sheet1") '新建工作表
newWs.Range("A1").Value = "bcde"
newWs.Range("B1").Value = "汇总值"
Dim j As Long
j = 2 '从第2行开始写入数据
For Each key In summaryDictionary.keys
    newWs.Cells(j, 1).Value = key
    newWs.Cells(j, 2).Value = summaryDictionary(key)
    j = j + 1
Next key

End Sub

需要注意的是,这段代码中使用了字典对象(Scripting.Dictionary),需要在代码窗口的工具菜单中选择“引用”->“Microsoft Scripting Runtime”,并勾选“Microsoft Scripting Dictionary”才能使用。


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

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