Option Explicit
Sub PivotByDictionary()
Dim sArr(), Res(), Dic As Object, Header As Range
Dim I As Long, R As Long, Col As Integer, nCol As Integer
Dim K As Long, lR As Long
'Tat nhay man hinh
Application.ScreenUpdating = False
'Khai bao thu vien Dictionary
Set Dic = CreateObject("Scripting.Dictionary")
'Dong tieu de
Set Header = Sheet1.Range("B5:F5")
'Dong cuoi cung co du lieu
lR = Sheet1.Range("B" & Rows.Count).End(xlUp).Row
'Mang 2 chieu chua toan bo du lieu
sArr() = Sheet1.Range("B6:F" & lR).Value
'Can tren cua chieu thu nhat mang sArr
R = UBound(sArr, 1)
'Quy dinh kich thuoc mang ket qua Res
ReDim Res(1 To R, 1 To UBound(sArr, 2) + 1)
'Can tren cua chieu thu hai mang Res
Col = UBound(Res, 2)
'Chay vong lap qua tung dong du lieu cua mang sArr
For I = 1 To R
'Kiem tra Ma san pham da ton tai trong Dictionary chua
If Not Dic.exists(sArr(I, 1)) Then
K = K + 1 'Tang thu tu
'Add ma san pham la Key vao Dic voi Item la thu tu
Dic.Add sArr(I, 1), K
'Chay vong lap qua tung cot de lay gia tri vao Res
For nCol = 1 To Col - 1
Res(K, nCol) = sArr(I, nCol)
Next nCol
'Cot cuoi cung de tinh so lan xuat hien cua tung Ma san pham
Res(K, Col) = 1
Else
'Truong hop ma san pham da ton tai
For nCol = 2 To Col - 1
Res(Dic.item(sArr(I, 1)), nCol) = Res(Dic.item(sArr(I, 1)), nCol) + sArr(I, nCol)
Next nCol
'So lan xuat hien tang them 1 lan so voi cu
Res(Dic.Item(sArr(I, 1)), Col) = Res(Dic.Item(sArr(I, 1)), Col) + 1
End If
Next I
'Tinh trung binh cong
For I = 1 To K
For nCol = 3 To Col - 1
Res(I, nCol) = Res(I, nCol) / Res(I, Col)
Next nCol
Next I
'Copy dong tieu de
Header.Copy Sheet1.Range("H12")
'Gan ket qua tu mang Res vao bang tinh
Sheet1.Range("H13").Resize(K, Col - 1) = Res
'Giai phong bo nho
Set Dic = Nothing
Set Header = Nothing
'Mo nhay man hinh
Application.ScreenUpdating = False
'Thong bao hoan thanh thu tuc
MsgBox "Done", vbInformation, "Daily Excel"
End Sub