Option Explicit
Sub test()
Dim arr, i, j, k, sum, total, n
With Sheets("sheet1")
arr = .Range("a2:f" & .Cells(Rows.Count, "c").End(xlUp).Row + 1)
End With
ReDim brr(1 To UBound(arr, 1) * 2, 1 To UBound(arr, 2))
Call bsort(arr, 3)
For i = 1 To UBound(arr, 1) - 1
For j = i To UBound(arr, 1) - 1
sum = sum + arr(j, 6)
n = n + 1
For k = 1 To UBound(arr, 2): brr(n, k) = arr(j, k): Next
If arr(j, 3) <> arr(j + 1, 3) Then
n = n + 1
brr(n, 1) = "小计": brr(n, 6) = sum
total = total + sum: sum = 0
i = j: Exit For
End If
Next j, i
n = n + 1: brr(n, 1) = "总计": brr(n, 6) = total
With Sheets("sheet2").[a2]
.Resize(Rows.Count - 1, UBound(brr, 2)).ClearContents
.Resize(n, UBound(brr, 2)) = brr
End With
End Sub
Function bsort(arr, key)
Dim i, j, k, t, move As Boolean
For i = LBound(arr, 1) To UBound(arr, 1) - 2
For j = LBound(arr, 1) To UBound(arr, 1) + LBound(arr, 1) - 2 - i
If arr(j, key) > arr(j + 1, key) Then
For k = LBound(arr, 2) To UBound(arr, 2)
t = arr(j, k): arr(j, k) = arr(j + 1, k): arr(j + 1, k) = t
Next
move = True
End If
Next
If Not move Then Exit For
Next
End Function |