Option Explicit
Sub TongHop()
Dim i&, J&, Lr&, t&, k&, R&, Col&, Tmr As Double
Dim Ws As Worksheet, Sh As Worksheet
Dim Arr(), KQ(), s
Dim Dic As Object, key As String
Dim Dict As Object, Temp As String
Tmr = Timer()
Set Sh = Sheets("Report")
ReDim KQ(1 To 1000000, 1 To 7)
ReDim TieuDe(1 To 1, 1 To 7)
Set Dic = CreateObject("Scripting.Dictionary")
Set Dict = CreateObject("Scripting.Dictionary")
For Each Ws In Worksheets
If Ws.Name <> Sh.Name Then
Lr = Ws.Cells(1000000, 1).End(xlUp).Row
Arr = Ws.Range("A3:D" & Lr).Value: R = UBound(Arr)
For i = 1 To R
Temp = Arr(i, 4)
If Not Dict.Exists(Temp) Then Col = Col + 1: Dict.Add (Temp), Col: TieuDe(1, Col + 1) = Temp
key = Arr(i, 2)
If Not Dic.Exists(key) Then
t = t + 1: Dic.Add (key), t
KQ(t, 1) = key
KQ(t, Dict.Item(Temp) + 1) = Arr(i, 3)
Else
k = Dic.Item(key)
KQ(k, Dict.Item(Temp) + 1) = KQ(k, Dict.Item(Temp) + 1) + Arr(i, 3)
End If
KQ(t, 7) = (KQ(t, 5) + KQ(t, 6)) - (KQ(t, 2) + KQ(t, 3) + KQ(t, 4))
Next i
End If
Next Ws
TieuDe(1, 1) = "Item": TieuDe(1, Col + 2) = "Total"
If t Then
Sh.Range("A2").Resize(1000000, 7).ClearContents
Sh.Range("A2").Resize(1, Col + 2) = TieuDe
Sh.Range("A3").Resize(t, 7) = KQ
End If
Set Dic = Nothing: Set Dict = Nothing
MsgBox Timer() - Tmr ' MsgBox "DONE"
End Sub