Sub test()
Dim lastRow As Long, r As Long, tenhang As String, dulieu(), banggia(), TH As Object
With ThisWorkbook.Worksheets("Sheet1")
.Range("G5").Resize(10 ^ 6).ClearContents ' xoa ket qua cu neu co
lastRow = .Range("B" & Rows.Count).End(xlUp).Row ' dong cuoi cung co du lieu trong cot B
If lastRow < 5 Then Exit Sub ' neu khong co du lieu thi don do choi
dulieu = .Range("B5:C" & lastRow).Value ' lay du lieu vao mang dulieu
lastRow = .Range("F" & Rows.Count).End(xlUp).Row ' dong cuoi cung co du lieu trong cot F
If lastRow < 5 Then Exit Sub ' neu khong co du lieu thi don do choi
banggia = .Range("F5:F" & lastRow + 1).Value ' lay du lieu vao mang dulieu
End With
Set TH = CreateObject("Scripting.Dictionary") ' tao tu dienco Ten Hang la KEY va gia la ITEM
TH.comparemode = vbTextCompare ' khong phan biet chu hoa chu thuong cua Ten Hang
For r = 1 To UBound(dulieu, 1) ' duyet tung dong du lieu va them (Ten Hang, Gia) vao tu dien TH
tenhang = dulieu(r, 1) ' Ten Hang
If tenhang <> "" Then
If Not TH.exists(tenhang) Then TH.Add tenhang, dulieu(r, 2) ' neu chua co Ten Hang thi them Ten Hang voi tu cach la KEY va gia voi tu cach la ITEM
End If
Next r
For r = 1 To UBound(banggia, 1) - 1 ' duyet Ten Hang trong Bang Gia, khong duyet dong lay du o cuoi
tenhang = banggia(r, 1) ' Ten Hang
If tenhang <> "" Then
If TH.exists(tenhang) Then
banggia(r, 1) = TH.Item(tenhang) ' neu co gia cua Ten Hang trong tu dien TH thi lay vao ket qua
Else
banggia(r, 1) = 0
End If
End If
Next r
ThisWorkbook.Worksheets("Sheet1").Range("G5").Resize(UBound(banggia, 1)).Value = banggia
Set TH = Nothing
End Sub