Sub Main()
Dim dicMST1: Set dicMST1 = CreateObject("Scripting.Dictionary")
DuyetMST1 dicMST1, ShPC.Range("B5", ShPC.Range("B" & Rows.Count).End(xlUp)).Value, _
ShPC.Range("D5", ShPC.Range("D" & Rows.Count).End(xlUp)).Value
Dim dicMST2: Set dicMST2 = CreateObject("Scripting.Dictionary")
DuyetMST2 dicMST2, ShM12.Range("B14", ShM12.Range("B" & Rows.Count).End(xlUp)).Value
Dim dicTen: Set dicTen = CreateObject("Scripting.Dictionary")
DuyetTen dicTen, dicMST1, dicMST2
Dim aX: aX = TinhTong(dicTen, dicMST2, ShM12.Range("B14", ShM12.Range("AK" & Rows.Count).End(xlUp)).Value, _
Array(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35))
Application.ScreenUpdating = False
ShM13.Range("B14").Resize(500000, UBound(aX, 2)).ClearContents
ShM13.Range("B14").Resize(UBound(aX), UBound(aX, 2)) = aX
Application.ScreenUpdating = True
End Sub
Sub DuyetMST1(iDic, iArrayMST, iArrayTen)
Dim x&
For x = LBound(iArrayTen) To UBound(iArrayTen)
iDic(iArrayMST(x, 1)) = iArrayTen(x, 1)
Next x
End Sub
Sub DuyetMST2(iDic, iArrayMST)
Dim x&
For x = LBound(iArrayMST) To UBound(iArrayMST)
iDic(iArrayMST(x, 1)) = iDic(iArrayMST(x, 1)) & "," & x
Next x
End Sub
Sub DuyetTen(iDic, iDic1, iDic2)
Dim sKey
For Each sKey In iDic2.Keys
iDic(iDic1(sKey)) = iDic(iDic1(sKey)) & "," & sKey
Next sKey
End Sub
Function TinhTong(iDicTen, iDicMST, iArray, iColumns)
ReDim aX(LBound(iArray) To UBound(iArray) + iDicMST.Count, LBound(iArray, 2) To UBound(iArray, 2) + 1)
Dim x&, y1&, y2&, y3&, ySum&, sTen, aMST, aIndex
For Each sTen In iDicTen.Keys
aMST = Split(iDicTen(sTen), ",")
For y1 = LBound(aMST) + 1 To UBound(aMST)
aIndex = Split(iDicMST(aMST(y1)), ",")
ySum = ySum + UBound(aIndex) + 1
For y2 = LBound(aIndex) + 1 To UBound(aIndex)
y3 = y3 + 1
For x = LBound(aX, 2) To UBound(aX, 2) - 1
aX(y3, x) = iArray(aIndex(y2), x)
Next x
For x = LBound(iColumns) To UBound(iColumns)
aX(ySum, iColumns(x)) = aX(ySum, iColumns(x)) + iArray(aIndex(y2), iColumns(x))
Next x
aX(y3, UBound(aX, 2)) = sTen
Next y2
y3 = y3 + 1
aX(y3, 1) = "Tong " & aMST(y1)
aX(y3, UBound(aX, 2)) = sTen
Next y1
Next sTen
TinhTong = aX
End Function