Option Explicit
Sub tinhtong()
Dim sArr(), Mau(), SL(), aMau(), aSL(), dic As Object
Dim eRow&, eCol&, sLine&, sRow&, sCol&, i&, iR&, j&, jC&, n&
Dim fDay As Date, iKey$, iMax, slMax#
Const dRow& = 22: Const fRow& = 3
Set dic = CreateObject("scripting.dictionary")
With Sheets("ANALYSIS ")
eRow = .Range("B" & Rows.Count).End(xlUp).Row 'Dong cuoi
eCol = .Cells(1, Columns.Count).End(xlToLeft).Column 'Cot cuoi
sLine = Int(eRow / 22) 'So Line
ReDim aMau(1 To sLine): ReDim aSL(1 To sLine)
ReDim Mau(1 To 21, 1 To 1): ReDim SL(1 To 21, 1 To eCol - 5)
For n = 1 To sLine
dic.Item(.Cells(fRow + (n - 1) * dRow, "B").Value) = n
aMau(n) = Mau: aSL(n) = SL
Next n
For j = 6 To eCol
jC = jC + 1
fDay = .Cells(1, j).Value
For i = 0 To 6
dic.Item(Format(fDay + i, "ddmmyy")) = jC
Next i
Next j
End With
With Sheets("PLAN")
eRow = .Range("B" & Rows.Count).End(xlUp).Row
eCol = .Cells(2, Columns.Count).End(xlToLeft).Column
sArr = .Range("B2", .Cells(eRow, eCol)).Value
End With
sRow = UBound(sArr): sCol = UBound(sArr, 2)
For j = 3 To sCol
sArr(1, j) = dic.Item(Format(sArr(1, j), "ddmmyy")) 'Thu tu cot mang SL
Next j
For i = 2 To sRow
n = dic.Item(sArr(i, 1))
iKey = sArr(i, 1) & "|" & sArr(i, 2)
If dic.exists(iKey) = False Then
iR = aMau(n)(21, 1) + 1 'Thu tu dong
dic.Add iKey, iR
aMau(n)(iR, 1) = sArr(i, 2)
aMau(n)(21, 1) = iR
End If
iR = dic.Item(iKey)
For j = 3 To sCol
jC = sArr(1, j)
If jC > 0 Then
If sArr(i, j) <> Empty Then
aSL(n)(iR, jC) = aSL(n)(iR, jC) + sArr(i, j)
End If
End If
Next j
Next i
With Sheets("ANALYSIS ")
sCol = UBound(SL, 2)
For n = 1 To sLine
iR = fRow + (n - 1) * dRow
.Cells(iR, "c").Resize(20) = aMau(n)
.Cells(iR, "F").Resize(20, sCol) = aSL(n)
'Tinh dong Tieu Chuan Tuan
sRow = aMau(n)(21, 1)
For j = 1 To sCol
iMax = Empty: slMax = 0
For i = 1 To sRow
If aSL(n)(i, j) <> Empty Then
If slMax < aSL(n)(i, j) Then
slMax = aSL(n)(i, j)
iMax = .Cells(iR + i - 1, "E")
End If
End If
Next i
.Cells(iR + 20, 5 + j) = iMax
Next j
Next n
End With
End Sub