Option Explicit
Sub XYZ()
Dim aKH(), aNhap(), res(), wb As Workbook, path$, dic As Object
Dim sRow&, i&, r&, k&, ik&
Dim kh$, soCT$, ngayCT As Date
On Error GoTo Thoat
Set dic = CreateObject("scripting.dictionary")
With Sheets("data_khach")
i = .Range("B1000000").End(xlUp).Row
If i < 6 Then MsgBox ("Khong co du lieu Khach Hang!"): Exit Sub
aKH = .Range("B6:F" & i).Value
End With
For i = 1 To UBound(aKH)
dic.Item(aKH(i, 1)) = i
Next i
Application.ScreenUpdating = False
With Sheets("data_nhap")
i = .Range("C1000000").End(xlUp).Row
If i < 7 Then
Application.ScreenUpdating = True
MsgBox ("Khong co du lieu Vat Tu!"): Exit Sub
End If
res = .Range("A7:K" & i).Value
.Range("A7:K" & i).Sort .Range("I7"), 1, .Range("J7"), , 1, Header:=xlNo
aNhap = .Range("C7:L" & i + 1).Value
.Range("A7:K" & i).Value = res
End With
sRow = UBound(aNhap) - 1
Sheets("file_mau").Copy
Application.DisplayAlerts = False
path = ThisWorkbook.path 'Duong dan luu file moi tao
ActiveWorkbook.SaveAs Filename:=path & "\kq_kiem_tra.xlsx"
Set wb = ActiveWorkbook
For i = 1 To sRow
If soCT <> aNhap(i, 8) Then
If dic.exists(aNhap(i, 9)) Then
k = 0
ik = dic.Item(aNhap(i, 9))
ngayCT = aNhap(i, 7) 'Ngay chung tu
soCT = aNhap(i, 8) 'So chung tu
Else
ik = 0
MsgBox ("So chung tu: " & aNhap(i, 8) & Chr(10) & _
"Khong tim thay ma Khach hang: " & aNhap(i, 9))
soCT = aNhap(i, 8)
End If
ReDim res(1 To sRow, 1 To 9)
End If
If ik > 0 Then
If soCT = aNhap(i, 8) Then
k = k + 1
res(k, 1) = k
res(k, 2) = aNhap(i, 1)
res(k, 5) = aNhap(i, 2)
res(k, 6) = aNhap(i, 3)
res(k, 7) = res(k, 6)
res(k, 8) = 0
End If
If soCT <> aNhap(i + 1, 8) Then
wb.Sheets("file_mau").Copy after:=wb.Sheets(Sheets.Count)
With wb.Sheets(Sheets.Count)
.Name = soCT
.Range("D3").Value = ngayCT
.Range("A8").Value = Replace(Replace(Replace(Replace(.Range("A8").Value, "#HD#", aKH(ik, 3)), _
"#Ngay#", Format(aKH(ik, 4), "dd/mm/yyyy")), "#KH#", aKH(ik, 2)), "#SP#", aKH(ik, 5))
.Range("A19:I22").ClearContents
If k > 4 Then
.Range("A20").Resize(k - 4).EntireRow.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
ElseIf k < 4 Then
.Range("A19").Resize(4 - k).EntireRow.Delete
End If
.Range("A19").Resize(k, 9) = res
End With
End If
End If
Next i
wb.Sheets("file_mau").Delete 'Xóa sheet trung gian "file_mau"
wb.Save
'wb.Close 'Dong file kq_kiem_tra.xlsx
Thoat:
If Err.Number > 0 Then MsgBox ("Dong file kq_kiem_tra.xlsx truoc khi chay code")
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Set wb = Nothing
End Sub