以下是VBA代码实现:

Sub Four_Condition_Summary() Dim wb As Workbook Dim ws As Worksheet Dim wsNew As Worksheet Dim lastRow As Long Dim i As Long Dim dict As Object Set dict = CreateObject("Scripting.Dictionary")

'打开当前工作簿
Set wb = ThisWorkbook
'选择要操作的工作表
Set ws = wb.ActiveSheet
'获取最后一行行号
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row

'循环读取数据并汇总
For i = 2 To lastRow
    '获取四个条件的值
    Dim conditionB As String
    conditionB = ws.Cells(i, "B").Value
    Dim conditionC As String
    conditionC = ws.Cells(i, "C").Value
    Dim conditionD As String
    conditionD = ws.Cells(i, "D").Value
    Dim conditionE As String
    conditionE = ws.Cells(i, "E").Value
    '获取数值列f的值
    Dim valueF As Double
    valueF = ws.Cells(i, "F").Value
    
    '将四个条件组成一个字符串,作为字典的键
    Dim key As String
    key = conditionB & "|" & conditionC & "|" & conditionD & "|" & conditionE
    
    '如果字典中已经存在该键,则将对应的数值列f的值累加
    If dict.Exists(key) Then
        dict(key) = dict(key) + valueF
    Else '否则将该键值对添加到字典中
        dict.Add key, valueF
    End If
Next i

'新建一个工作表,将分类汇总结果放在其中
Set wsNew = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
wsNew.Name = "Sheet1"

'在新工作表中写入表头
wsNew.Cells(1, "A").Value = "条件B"
wsNew.Cells(1, "B").Value = "条件C"
wsNew.Cells(1, "C").Value = "条件D"
wsNew.Cells(1, "D").Value = "条件E"
wsNew.Cells(1, "E").Value = "汇总结果"

'循环遍历字典中的键值对,将结果写入新工作表中
Dim row As Long
row = 2
For Each key In dict
    wsNew.Cells(row, "A").Value = Split(key, "|")(0)
    wsNew.Cells(row, "B").Value = Split(key, "|")(1)
    wsNew.Cells(row, "C").Value = Split(key, "|")(2)
    wsNew.Cells(row, "D").Value = Split(key, "|")(3)
    wsNew.Cells(row, "E").Value = dict(key)
    row = row + 1
Next key

End Sub

使用方法:将以上代码复制到VBA编辑器中,然后在Excel中打开要操作的工作簿,按下快捷键Alt+F8打开宏窗口,选择要执行的宏Four_Condition_Summary并点击运行即可。执行完毕后,会在当前工作簿新建一个工作表Sheet1,其中包含了分类汇总结果。

做个vba四条件分类汇总bcde四列为条件f列为数值列对相同的bcde进行f列数据汇总新建1个workbook把分类汇总结果放在新工作表sheet1中bcde放条件结果f列为汇总结果

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

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