Sub NgayNhapKho()
Dim sArr(), res(), dic As Object, maVT$
Dim sRow&, i&, r&, tmp#
Set dic = CreateObject("scripting.dictionary")
With Sheets("tong hop nxt 18")
sArr = .Range("B13:E" & .Range("B" & Rows.Count).End(xlUp).Row).Value
End With
sRow = UBound(sArr)
For i = 1 To sRow
If sArr(i, 1) <> Empty And sArr(i, 4) <> Empty Then dic.Add sArr(i, 1), sArr(i, 4)
Next i
With Sheets("bang ke nxt 18")
i = .Range("C" & Rows.Count).End(xlUp).Row
.Range("C13:L" & i).Sort .[C13], 1, .[D13], , 1, .[E13], 1, xlNo
sArr = .Range("C13:J" & i).Value
End With
sRow = UBound(sArr)
ReDim res(1 To sRow, 1 To 4)
For i = 1 To sRow
If res(i, 1) = Empty Then
res(i, 1) = sArr(i, 1) 'Ngay
If sArr(i, 8) <> Empty Then
maVT = sArr(i, 7)
If sArr(i, 2) <> Empty Then
res(i, 2) = sArr(i, 8) 'Nhap
Else
res(i, 3) = sArr(i, 8) 'Xuat
End If
tmp = dic.Item(maVT) + res(i, 2) - res(i, 3)
If tmp >= 0 Then 'Ton duong
dic.Item(maVT) = tmp
Else 'Ton am
For r = i + 1 To sRow
If maVT = sArr(r, 7) And sArr(r, 2) <> Empty And sArr(r, 8) <> Empty Then
res(r, 1) = sArr(i, 1) - 1 'Truoc 1 Ngay
res(r, 2) = sArr(r, 8) 'Nhap
dic.Item(maVT) = dic.Item(maVT) + res(r, 2)
tmp = tmp + sArr(r, 8)
If tmp >= 0 Then
dic.Item(maVT) = tmp
Exit For
End If
End If
Next r
End If
End If
End If
Next i
With Sheets("bang ke nxt 18")
.Range("M13").Resize(sRow, 3) = res
.Range("C13").Resize(sRow, 13).Sort .[M13], 1, .[D13], , 1, .[E13], 1, xlNo
End With
Call TonCuoi
End Sub
Private Sub TonCuoi()
Dim sArr(), res(), dic As Object, maVT$
Dim sRow&, i&, tmp#
Set dic = CreateObject("scripting.dictionary")
With Sheets("tong hop nxt 18")
sArr = .Range("B13:E" & .Range("B" & Rows.Count).End(xlUp).Row).Value
End With
sRow = UBound(sArr)
For i = 1 To sRow
If sArr(i, 1) <> Empty And sArr(i, 4) <> Empty Then dic.Add sArr(i, 1), sArr(i, 4)
Next i
With Sheets("bang ke nxt 18")
sArr = .Range("I13:P" & .Range("I" & Rows.Count).End(xlUp).Row).Value
End With
sRow = UBound(sArr)
ReDim res(1 To sRow, 1 To 1)
For i = 1 To sRow
If sArr(i, 2) <> Empty Then
maVT = sArr(i, 1)
tmp = dic.Item(maVT) + sArr(i, 6) - sArr(i, 7)
dic.Item(maVT) = tmp
res(i, 1) = Round(tmp, 8)
End If
Next i
Sheets("bang ke nxt 18").Range("P13").Resize(sRow) = res
End Sub