根据列值合并来自不同行的数据

Combine data from different rows base on column value

我有一个包含每日订单记录的excel文件,我需要根据不同的员工汇总订单详情。

我想合并基于相同员工 ID 的行并分成不同的组。
所有具有相同Staff ID(B列)的订单将被划分到同一组,组内订单的商品A到商品X的数量将单独相加,每个组将只保留第一个订单记录和其他订单ID (A栏)组内的会在备注栏(G栏)注明。

我有一个包含许多 for-loop 和 if 语句的宏来完成任务,但我不知道如何简化或修改它。有人可以给我一些建议吗?

如果我能为您澄清任何事情,请告诉我。

Private Sub test()
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
'sum the quantity of item
For Z = 2 To lastrow
If Range("F" & Z) <> "" Then
    ordercount = 2
    For c = 2 To lastrow
        If Z <> c Then
            If Range("F" & Z) = Range("F" & c) Then
                For i = 0 To 9
                    temp = Cells(Z, 3 + i) + Cells(c, 3 + i)
                    If temp <> 0 Then
                        Cells(Z, 3 + i) = temp
                    End If
                Next i
                Range("G" & Z) = Range("G" & Z).Value & "No." & ordercount 
                & " " & Range("A" & c).Value & Chr(10)
                ordercount = ordercount + 1
                End If
        End If
    Next c
End If
orderno = Range("G" & Z).Value
If orderno <> "" Then
    Range("G" & Z) = Left(orderno, Len(orderno) - 1)
End If
Next Z
'delete the other record within the same group
For Z = 2 To lastrow
If Range("F" & Z) <> "" Then
    For c = 2 To lastrow
        If Z <> c Then
            If Range("F" & Z) = Range("F" & c) Then
                Rows(c).Delete
                c = c - 1
            End If
        End If
    Next c
End If
Next Z
End Sub

样本:

以下将按您的预期执行,但循环从数据的底部开始并移动到第二行,因为删除行时建议向上工作,以免错过与任何数据的比较删除行时的行数:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A

For i = LastRow To 2 Step -1 'loop from last row to second (missing headers)
    CheckID = ws.Cells(i, 2) 'get the Staff ID to check
    For x = (i - 1) To 2 Step -1 'second loop for comparison
        If ws.Cells(x, 2) = CheckID Then 'if ID's match
            ws.Cells(i, 3) = ws.Cells(i, 3) + ws.Cells(x, 3) 'add values for Item A
            ws.Cells(i, 4) = ws.Cells(i, 4) + ws.Cells(x, 4) 'add values for Item B
            ws.Cells(i, 5) = ws.Cells(i, 5) + ws.Cells(x, 5) 'add values for Item C
            ws.Cells(i, 6) = ws.Cells(i, 6) 'get the Group Number
            ws.Cells(i, 7) = ws.Cells(i, 7) & Chr(10) & ws.Cells(x, 1) 'Add remark
            ws.Rows(x).Delete Shift:=xlUp 'delete row
            i = i - 1 'adjust counter
            LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'get new last row
        End If
    Next x
Next i
End Sub