Option Explicit
Sub xyz()
Dim arr(), bom2(), bom3(), aTD(), a
Dim dSP As Object, d As Object, d2 As Object, b2 As Object, b3 As Object
Dim sR&, sC&, i&, r2&, r3&, k&, c&, j&, vt$
Set d = CreateObject("scripting.dictionary")
Set d2 = CreateObject("scripting.dictionary")
Set dSP = CreateObject("scripting.dictionary")
Set b2 = CreateObject("scripting.dictionary")
Set b3 = CreateObject("scripting.dictionary")
aTD = Sheets("BOM2").Range("A2:C3").Value 'Mang dong tieu de
sC = UBound(aTD, 2) 'So cot tieu de thong tin vat tu
With Sheets("BOM1")
arr = .Range("A2", .Range("G" & Rows.Count).End(xlUp)).Value
End With
sR = UBound(arr)
For i = 1 To sR
d(arr(i, 1)) = d(arr(i, 1)) & "," & i
d2(arr(i, 4)) = ""
Next i
For i = 1 To sR 'Loc San Pham
If d2.exists(arr(i, 1)) = False Then
If dSP.exists(arr(i, 1)) = False Then
sC = sC + 1
dSP(arr(i, 1)) = sC
ReDim Preserve aTD(1 To 2, 1 To sC)
aTD(1, sC) = arr(i, 2)
aTD(2, sC) = arr(i, 1)
End If
End If
Next
ReDim bom2(1 To sR, 1 To sC)
ReDim bom3(1 To sR, 1 To sC)
For c = 4 To sC
a = Split(d(aTD(2, c)), ",")
For j = 1 To UBound(a)
i = CLng(a(j))
vt = arr(i, 4)
If b2.exists(vt) = False Then
r2 = r2 + 1
b2(vt) = r2
End If
k = b2(vt)
bom2(k, 1) = arr(i, 4): bom2(k, 2) = arr(i, 5)
bom2(k, 3) = arr(i, 6): bom2(k, c) = bom2(k, c) + arr(i, 7)
If b3.exists(vt) = False Then
r3 = r3 + 1
b3(vt) = r3
End If
k = b3(vt)
bom3(k, 1) = arr(i, 4): bom3(k, 2) = arr(i, 5)
bom3(k, 3) = arr(i, 6): bom3(k, c) = bom3(k, c) + arr(i, 7)
If d.exists(vt) Then
Call DeQui(arr, bom2, bom3, d, b2, b3, r2, r3, c, Split(d(vt), ","), arr(i, 7))
End If
Next j
Next c
Sheets("BOM2").Range("A2").Resize(2, sC) = aTD
Sheets("BOM2").Range("A4").Resize(r2, sC) = bom2
Sheets("BOM3").Range("A2").Resize(2, sC) = aTD
Sheets("BOM3").Range("A4").Resize(r3, sC) = bom3
End Sub
Sub DeQui(arr, bom2, bom3, d, b2, b3, r2, r3, c, ByVal a, ByVal sl#)
Dim vt$, j&, i&, k&
For j = 1 To UBound(a)
i = CLng(a(j))
vt = arr(i, 4)
If b2.exists(vt) = False Then
r2 = r2 + 1
b2(vt) = r2
End If
k = b2(vt)
bom2(k, 1) = arr(i, 4): bom2(k, 2) = arr(i, 5)
bom2(k, 3) = arr(i, 6): bom2(k, c) = bom2(k, c) + arr(i, 7) * sl
If d.exists(vt) Then
Call DeQui(arr, bom2, bom3, d, b2, b3, r2, r3, c, Split(d(vt), ","), arr(i, 7) * sl)
Else
If b3.exists(vt) = False Then
r3 = r3 + 1
b3(vt) = r3
End If
k = b3(vt)
bom3(k, 1) = arr(i, 4): bom3(k, 2) = arr(i, 5)
bom3(k, 3) = arr(i, 6): bom3(k, c) = bom3(k, c) + arr(i, 7) * sl
End If
Next j
End Sub