如何获取Excel分组中最大Cost对应的Sale-ID?(VBA方案)
Excel VBA实现分组找最大值对应Sale-ID的思路指引
因为你的A、B列已经排序,这可以大幅简化代码逻辑,不用额外处理分组去重,直接遍历即可。以下是具体实现思路和关键代码:
核心逻辑步骤
- 先记录当前分组的A、B值,同时初始化该分组的最大Cost值和对应的Sale-ID
- 逐行遍历数据:
- 若当前行的A、B值和记录的分组一致,就对比D列Cost值,比当前最大值大的话,更新最大值和对应的C列Sale-ID
- 若A、B值变化,说明当前分组遍历结束,把结果写入目标区域(F:J),再切换到新分组重复操作
- 遍历结束后,别忘了写入最后一个分组的结果
关键代码示例
Sub GetMaxCostSaleID() Dim ws As Worksheet Dim lastRow As Long, resultRow As Long Dim i As Long Dim currentA As Variant, currentB As Variant Dim maxCost As Double, maxSaleID As Variant ' 替换成你的工作表名称 Set ws = ThisWorkbook.Sheets("Sheet1") ' 获取数据最后一行 lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' 结果起始行(假设F1是表头,从F2开始写) resultRow = 2 ' 初始化第一个分组的信息 currentA = ws.Cells(2, "A").Value currentB = ws.Cells(2, "B").Value maxCost = ws.Cells(2, "D").Value maxSaleID = ws.Cells(2, "C").Value ' 从第3行开始遍历(假设第1行是表头) For i = 3 To lastRow ' 判断是否属于当前分组 If ws.Cells(i, "A").Value = currentA And ws.Cells(i, "B").Value = currentB Then ' 检查Cost是否更大,同时处理非数值情况 If IsNumeric(ws.Cells(i, "D").Value) And ws.Cells(i, "D").Value > maxCost Then maxCost = ws.Cells(i, "D").Value maxSaleID = ws.Cells(i, "C").Value End If Else ' 写入上一个分组的结果到F:J区域 ws.Cells(resultRow, "F").Value = currentA ws.Cells(resultRow, "G").Value = currentB ws.Cells(resultRow, "H").Value = maxSaleID ws.Cells(resultRow, "I").Value = maxCost ' 若J列需要内容,可在这里添加,比如ws.Cells(resultRow, "J").Value = "备注" ' 更新为新分组的信息 currentA = ws.Cells(i, "A").Value currentB = ws.Cells(i, "B").Value maxCost = ws.Cells(i, "D").Value maxSaleID = ws.Cells(i, "C").Value resultRow = resultRow + 1 End If Next i ' 写入最后一个分组的结果 ws.Cells(resultRow, "F").Value = currentA ws.Cells(resultRow, "G").Value = currentB ws.Cells(resultRow, "H").Value = maxSaleID ws.Cells(resultRow, "I").Value = maxCost End Sub
新手注意事项
- 一定要把代码里的
Sheet1改成你实际的工作表名称 - 运行代码前先备份数据,避免误操作导致数据丢失
- 如果D列存在非数值内容,代码里的
IsNumeric判断会跳过这些行,防止报错 - 如果同一分组有多个相同的最大值,代码默认保留最后一个出现的Sale-ID;要是需要第一个,把比较条件改成
>=即可
内容的提问来源于stack exchange,提问作者Shmuel A. Kam
相关产品推荐
相关产品推荐

