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

时间:2018-02-02 09:06:17

标签: excel-vba excel-2007 vba excel

我有一个包含每日订单记录的Excel文件,我需要总结不同员工的订单明细。

我想将基于相同员工ID的行组合并划分为不同的组 所有具有相同员工ID(B列)的订单将划分为同一个组,组中订单的项目A到项目X的数量将汇总个别,每个组将仅保留第一个订单记录而另一个订单ID组中的(A列)将在备注栏(G栏)中标记。

我有一个带有许多for-loop和amp;的宏。如果声明完成任务,但我不知道如何简化或修改它。有人可以给我一些建议吗?

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

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

样品:

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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