Option Explicit
Public Sub NXT()
Dim Dic As Object, ArrN(), ArrX(), ArrT(), Tmp As String
Dim I As Long, J As Long, K As Long, R As Long, Rws As Long
Set Dic = CreateObject("Scripting.Dictionary")
ArrN = Sheets("Nhap").Range("B1", Sheets("Nhap").Range("B100000").End(xlUp)).Resize(, 4).Value
ArrX = Sheets("Xuat").Range("B1", Sheets("Xuat").Range("B100000").End(xlUp)).Resize(, 4).Value
R = UBound(ArrN)
'=============================================== Nhap'
If R = 1 Then Exit Sub 'Khong Nhap thi sao co Ton'
ReDim ArrT(1 To R, 1 To 4)
For I = 2 To R
Tmp = ArrN(I, 1) & "#" & ArrN(I, 3) 'Ma hang va So lo'
If Not Dic.Exists(Tmp) Then
K = K + 1
Dic.Item(Tmp) = K
For J = 1 To 4
ArrT(K, J) = ArrN(I, J)
Next J
Else
Rws = Dic.Item(Tmp)
ArrT(Rws, 4) = ArrT(Rws, 4) + ArrN(I, 4)
End If
Next I
'=============================================== Xuat'
R = UBound(ArrX)
If R > 1 Then
On Error Resume Next 'Khong Nhap ma Xuat la Tao Lao: Bo qua'
For I = 2 To R
Rws = Dic.Item(ArrX(I, 1) & "#" & ArrX(I, 3))
ArrT(Rws, 4) = ArrT(Rws, 4) - ArrX(I, 4)
Next I
End If
'=============================================== Ton'
Sheets("Ton").Range("A2").Resize(10000, 4).ClearContents
Sheets("Ton").Range("A2").Resize(K, 4) = ArrT
Set Dic = Nothing
End Sub