|
Sub 分类汇总()
Application.ScreenUpdating = False
Dim ar As Variant
Dim d As Object, dc As Object
Set d = CreateObject("scripting.dictionary")
Set dc = CreateObject("scripting.dictionary")
With Sheets("明细")
r = .Cells(Rows.Count, 1).End(xlUp).Row
If r < 2 Then MsgBox "明细为空!": End
ar = .Range("a1:e" & r)
End With
For i = 2 To UBound(ar)
If Trim(ar(i, 2)) <> "" Then
d(Trim(ar(i, 2))) = ""
End If
Next i
ReDim br(1 To UBound(ar), 1 To 500)
k = 3
br(1, 2) = kk
br(3, 1) = "Row Labels"
With Sheets("分类汇总")
.UsedRange = Empty
For Each kk In d.keys
For i = 2 To UBound(ar)
If Trim(ar(i, 2)) = kk Then
t = dc(Trim(ar(i, 1)))
If t = "" Then
k = k + 1
dc(Trim(ar(i, 1))) = k
t = k
br(k, 1) = ar(i, 1)
End If
lh = dc(Trim(ar(i, 3)))
If lh = "" Then
y = y + 2
dc(Trim(ar(i, 3))) = y
lh = y
br(1, y) = kk
br(2, y) = ar(i, 3)
br(3, y) = "Sum of 销售"
br(3, y + 1) = "Sum of 利润率"
End If
br(t, lh) = br(t, lh) + ar(i, 4)
br(t, lh + 1) = br(t, lh + 1) + ar(i, 5)
End If
Next i
For i = 2 To UBound(ar)
If Trim(ar(i, 2)) = kk Then
lh = dc(kk & "Sum of 销售")
If lh = "" Then
y = y + 2
dc(kk & "Sum of 销售") = y
lh = y
br(3, y) = kk & "Sum of 销售"
End If
br(3, y + 1) = kk & "Sum of 利润率"
t = dc(Trim(ar(i, 1)))
br(t, lh) = br(t, lh) + ar(i, 4)
br(t, lh + 1) = br(t, lh + 1) + ar(i, 5)
End If
Next i
Next kk
k = k + 1
br(k, 1) = "Grand Total"
For j = 2 To y + 1 Step 1
For i = 4 To k - 1
br(k, j) = br(k, j) + br(i, j)
Next i
Next j
For j = 3 To y + 1 Step 2
For i = 4 To k
br(i, j) = br(i, j) / br(i, j - 1)
Next i
Next j
.Cells(1, 1).Resize(k, y + 1) = br
.Columns("a:bb").AutoFit
End With
Application.ScreenUpdating = True
MsgBox "ok!"
End Sub
|
|