Sub GPE()
Dim Dic As Object, iKey As String, Wb As Workbook, FileName As String
Dim sArr(), Res(), Cap(1 To 4)
Dim i As Long, j As Long, sRow As Long, k As Long, n As Long, jCol As Long
Dim Tmp As String, Tmp1 As String, Tmp2 As String
Const C1 = ".I.II.III.IV.V.VI.VII.VIII.IX."
Const C2 = "/A/B/C/D/E/F/H/"
Const C3 = "/I/II/III/IV/V/VI/VII/VIII/IX/"
sArr = Range("A4:C" & Range("B" & Rows.Count).End(xlUp).Row + 1).Value
sRow = UBound(sArr)
ReDim Res(1 To sRow - 1, 1 To 1)
Set Dic = CreateObject("scripting.dictionary")
For i = 1 To sRow - 1
Tmp1 = Application.Trim(sArr(i, 1)): Tmp2 = Replace(UCase(Application.Trim(sArr(i, 2))), ":", "")
If InStr(1, Tmp2, ".") Then Tmp2 = Mid(Tmp2, 1, InStr(1, Tmp2, "."))
If Len(sArr(i, 3)) = 0 Then
If Len(Tmp1) + Len(Tmp2) > 0 Then
If Len(Tmp1) > 0 Then Tmp = Tmp1 Else Tmp = Tmp2
If InStr(1, C2, "/" & Tmp) Then
k = 2: Cap(k) = Tmp
n = 0
ElseIf InStr(1, C1, "." & Tmp) Then
k = 1: Cap(k) = Tmp
n = 0
ElseIf InStr(1, C3, "/" & Tmp) Then
k = 3: Cap(k) = Tmp
n = 0
ElseIf IsNumeric(Mid(Tmp, 1, 1)) Then
Tmp = Replace(Tmp, "/", ".")
Tmp = Mid(Tmp, 1, InStr(1, Tmp, "."))
k = 4: Cap(k) = Tmp
n = 0
Else
n = n + 1
k = 4: Cap(k) = n
End If
End If
If Len(sArr(i + 1, 3)) > 0 Then
Tmp = ""
For j = 1 To k
Tmp = Tmp & "#" & Cap(j)
Next j
End If
Else
iKey = Tmp & "#" & Tmp1 & "#" & Left(Tmp2, 10)
Dic.Add iKey, i
End If
Next i
FileName = GetFile(ThisWorkbook.Path)
If Len(FileName) Then
Tmp = UCase(FileName)
For j = 5 To 100
If InStr(1, Tmp, UCase(Cells(1, j))) Then
jCol = j: Exit For
End If
Next j
'Ten file phai phu hop voi tieu de cot, neu khong phu hop cot se khong chay
If jCol = 0 Then MsgBox ("Ten File khong dung tieu de cot"): Exit Sub
Set Wb = Workbooks.Open(FileName, False)
With Wb.Sheets(1)
sArr = .Range("B7:J" & .Range("D" & Rows.Count).End(xlUp).Row + 1).Value
sRow = UBound(sArr)
End With
Wb.Close False
For i = 1 To sRow - 1
Tmp1 = Application.Trim(sArr(i, 1)): Tmp2 = Replace(UCase(Application.Trim(sArr(i, 3))), ":", "")
If InStr(1, Tmp2, ".") Then Tmp2 = Mid(Tmp2, 1, InStr(1, Tmp2, "."))
If TypeName(sArr(i, 4)) = "Error" Then sArr(i, 4) = ""
If TypeName(sArr(i + 1, 4)) = "Error" Then sArr(i + 1, 4) = ""
If Len(sArr(i, 4)) = 0 Then
If Len(Tmp1) + Len(Tmp2) > 0 Then
If Len(Tmp1) > 0 Then Tmp = Tmp1 Else Tmp = Tmp2
If InStr(1, C2, "/" & Tmp) Then
k = 2: Cap(k) = Tmp
n = 0
ElseIf InStr(1, C1, "." & Tmp) Then
k = 1: Cap(k) = Tmp
n = 0
ElseIf InStr(1, C3, "/" & Tmp) Then
k = 3: Cap(k) = Tmp
n = 0
ElseIf IsNumeric(Mid(Tmp, 1, 1)) Then
Tmp = Replace(Tmp, "/", ".")
Tmp = Mid(Tmp, 1, InStr(1, Tmp, "."))
k = 4: Cap(k) = Tmp
n = 0
Else
n = n + 1
k = 4: Cap(k) = n
End If
End If
If Len(sArr(i + 1, 4)) > 0 Then
Tmp = ""
For j = 1 To k
Tmp = Tmp & "#" & Cap(j)
Next j
End If
Else
iKey = Tmp & "#" & Tmp1 & "#" & Left(Tmp2, 10)
If Dic.exists(iKey) = True Then
Res(Dic.Item(iKey), 1) = sArr(i, 7)
End If
End If
Next i
Cells(4, jCol).Resize(UBound(Res)) = Res
End If
End Sub