Sub ABC()
Dim aData(), aKH(), Res(), dic As Object
Dim sRow&, i&, k&, ik&, Co&
Dim TK$, maKH$, soDu#, fDay As Date, eDay As Date
Set dic = CreateObject("Scripting.Dictionary")
With Sheet19
fDay = .Range("F1").Value
eDay = .Range("H1").Value
End With
With Sheet5
aData = .Range("A3:N" & .Range("B" & Rows.Count).End(xlUp).Row).Value
End With
sRow = UBound(aData)
ReDim Res(1 To sRow, 1 To 8)
For i = 1 To sRow
If aData(i, 12) = "131" Or aData(i, 13) = "131" Then
If aData(i, 12) = "131" Then Co = 0 Else Co = 1
maKH = aData(i, 7 + Co * 2)
If dic.exists(maKH) = False Then
k = k + 1
dic.Add maKH, k
Res(k, 1) = maKH
Res(k, 2) = aData(i, 8 + Co * 2)
End If
ik = dic.Item(maKH)
If aData(i, 2) < fDay Then
Res(ik, 3 + Co) = Res(ik, 3 + Co) + aData(i, 14)
ElseIf aData(i, 2) <= eDay Then
Res(ik, 5 + Co) = Res(ik, 5 + Co) + aData(i, 14)
End If
End If
Next i
With Sheet9
aKH = .Range("A3:E" & .Range("B" & Rows.Count).End(xlUp).Row).Value
End With
sRow = UBound(aKH)
For i = 1 To sRow 'Chi xet Khach Hang co du dau ky hoac phat sinh trong ky
If aKH(i, 3) + aKH(i, 4) > 0 Then
maKH = aKH(i, 1)
If dic.exists(maKH) Then
ik = dic.Item(maKH)
Res(ik, 3) = Res(ik, 3) + aKH(i, 3)
Res(ik, 4) = Res(ik, 4) + aKH(i, 4)
Else
k = k + 1
Res(k, 1) = maKH: Res(k, 2) = aKH(i, 2)
Res(k, 3) = aKH(i, 3): Res(k, 4) = aKH(i, 4)
End If
End If
Next i
For i = 1 To k
soDu = Res(i, 3) + Res(i, 5) - Res(i, 4) - Res(i, 6)
If soDu >= 0 Then Res(i, 7) = soDu Else Res(i, 8) = -soDu
Next i
With Sheet19
i = .Range("B" & Rows.Count).End(xlUp).Row
If i > 9 Then .Range("A10:H" & i).ClearContents
If k > 0 Then .Range("A10").Resize(k, 8).Value = Res
End With
Set dic = Nothing
End Sub