Sub XYZ()
Dim aTon(), aNhap(), aXuat(), res()
Dim sRow&, i&, r&, ngay As Date, cod$, sl&
With Sheets("BaoCao")
i = .Range("B" & Rows.Count).End(xlUp).Row
If i < 8 Then i = 8
aTon = .Range("B8", .Range("E" & i)).Value
End With
With Sheets("Nhap")
i = .Range("A" & Rows.Count).End(xlUp).Row
If i < 5 Then i = 5
aNhap = .Range("A5", .Range("M" & i)).Value
End With
With Sheets("Xuat")
i = .Range("C" & Rows.Count).End(xlUp).Row
If i < 6 Then MsgBox ("Khong co Xuat!"): Exit Sub
aXuat = .Range("C6", .Range("K" & i)).Value
End With
sRow = UBound(aXuat)
ReDim res(1 To sRow, 1 To 1)
For i = 1 To sRow
ngay = aXuat(i, 1)
cod = aXuat(i, 5)
sl = aXuat(i, 9)
For r = UBound(aNhap) To 1 Step -1
If aNhap(r, 4) = cod Then
If aNhap(r, 1) <= ngay Then
If aNhap(r, 10) > 0 Then
res(i, 1) = aNhap(r, 13) & ", " & res(i, 1)
If aNhap(r, 10) < sl Then
sl = sl - aNhap(r, 10)
aNhap(r, 10) = 0
Else
aNhap(r, 10) = aNhap(r, 10) - sl
sl = 0
Exit For
End If
End If
End If
End If
Next r
If sl > 0 Then
For r = 1 To UBound(aTon)
If aTon(r, 1) = cod Then
If aTon(r, 4) > 0 Then
res(i, 1) = "Ton, " & res(i, 1)
If aTon(r, 4) < sl Then
sl = sl - aTon(r, 4)
aTon(r, 4) = 0
Else
aTon(r, 4) = aTon(r, 4) - sl
sl = 0
End If
End If
End If
Next r
End If
If sl > 0 Then res(i, 1) = "(Khong du xuat)" & res(i, 1)
res(i, 1) = Mid(res(i, 1), 1, Len(res(i, 1)) - 2)
Next i
Sheets("Xuat").Range("O6").Resize(sRow) = res
End Sub