Option Explicit
Dim dicTt As Object
Sub loc()
Dim nguon
Dim huyen
Dim ds, cv, tam
Dim rws, i, j, k, x, z
With Sheet1
nguon = .Range("A4", "E" & .Range("D4").End(xlDown).Row)
huyen = .Range("G3")
rws = UBound(nguon)
End With
If dicTt Is Nothing Then
Set dicTt = CreateObject("Scripting.Dictionary")
For i = 1 To rws
z = Left(nguon(i, 4), 1)
If dicTt.Exists(nguon(i, 3)) = False Then
ReDim tam(1 To rws, 1 To 5)
ReDim ds(1 To rws, 1 To 1)
ds(1, 1) = nguon(i, 2)
ReDim cv(1 To rws, 1 To 5)
For j = 1 To 5
cv(1, j) = nguon(i, j)
Next j
'ten; chanhan; thamphan; nhanvie; ketoan
If z = "C" Then dicTt(nguon(i, 3)) = Array(Array(1, ds), Array(1, cv), Array(0, tam), Array(0, tam), Array(0, tam))
If z = "T" Then dicTt(nguon(i, 3)) = Array(Array(1, ds), Array(0, tam), Array(1, cv), Array(0, tam), Array(0, tam))
If z = "N" Then dicTt(nguon(i, 3)) = Array(Array(1, ds), Array(0, tam), Array(0, tam), Array(1, cv), Array(0, tam))
If z = "K" Then dicTt(nguon(i, 3)) = Array(Array(1, ds), Array(0, tam), Array(0, tam), Array(0, tam), Array(1, cv))
Else
tam = dicTt(nguon(i, 3))
ds = tam(0)(1)
k = tam(0)(0)
k = k + 1
ds(k, 1) = nguon(i, 2)
tam(0) = Array(k, ds)
If z = "C" Then k = 1
If z = "T" Then k = 2
If z = "N" Then k = 3
If z = "K" Then k = 4
cv = tam(k)(1)
x = tam(k)(0) + 1
For j = 1 To 5
cv(x, j) = nguon(i, j)
Next j
tam(k) = Array(x, cv)
dicTt(nguon(i, 3)) = tam
End If
Next i
End If
For Each k In Worksheets
If k.Name <> "TongHop" Then k.Range("A4").Resize(rws, 5).ClearContents
Next k
Sheet1.Range("G5", "G" & rws + 5).ClearContents
If huyen = "" Then
For Each tam In dicTt.Items
k = tam(1)(0)
ds = tam(1)(1)
If k > 0 Then Sheet2.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(2)(0)
ds = tam(2)(1)
If k > 0 Then Sheet3.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(3)(0)
ds = tam(3)(1)
If k > 0 Then Sheet4.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(4)(0)
ds = tam(4)(1)
If k > 0 Then Sheet5.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
Next tam
Else
tam = dicTt(huyen)
Sheet1.Range("G5").Resize(tam(0)(0), 1) = tam(0)(1)
k = tam(1)(0)
ds = tam(1)(1)
If k > 0 Then Sheet2.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(2)(0)
ds = tam(2)(1)
If k > 0 Then Sheet3.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(3)(0)
ds = tam(3)(1)
If k > 0 Then Sheet4.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
k = tam(4)(0)
ds = tam(4)(1)
If k > 0 Then Sheet5.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(k, 5) = ds
End If
End Sub