My requirement is that family tree is required with sorting. Kindly check the snaps attached in which question shows how the data is & Answer shows the data in required format.
Code is performing above tasks perfectly with dictionaries used. Now, the requirement is that it should be done with 1 sub routine.
I am stuck that how it can be done with one sub routine as for family tree, iterative function is required.
Kindly check & any help is highly appreciated.
>>> use code - tags <<<
Code is performing above tasks perfectly with dictionaries used. Now, the requirement is that it should be done with 1 sub routine.
I am stuck that how it can be done with one sub routine as for family tree, iterative function is required.
Kindly check & any help is highly appreciated.
>>> use code - tags <<<
Code:
Sub Demo()
Set nws = Worksheets("newsheet")
Dim i As Long, j As Long, objDic As Object
Dim arrData, rngData As Range, aRow(1 To 4)
Dim sParent As String, sChild As String, sFirst As String
Set rngData = nws.Range("A1").CurrentRegion 'A1
' load data into an array
arrData = rngData.Value
ReDim arrRes(1 To UBound(arrData), 1 To 4)
' populate header
iR = 1
For j = 1 To 4
arrRes(iR, j) = arrData(1, j)
Next
Set objDic = CreateObject("scripting.dictionary")
' loop through data
For i = LBound(arrData) To UBound(arrData)
If arrData(i, 1) = 1 Then ' top node of each family
If Len(sFirst) > 0 Then
Call GetChild(objDic, "", sFirst)
' reset Dict
objDic.RemoveAll
End If
sFirst = arrData(i, 3)
End If
sParent = arrData(i, 2): sChild = arrData(i, 3)
If Not objDic.exists(sParent) Then
Set objDic(sParent) = CreateObject("scripting.dictionary")
End If
' get data row
For j = 1 To 4
aRow(j) = arrData(i, j)
Next
' add to Dict
objDic(sParent)(sChild) = aRow()
Next i
GetChild objDic, "", sFirst
' write output to sheet (starts from cell F1), modify as needed
With nws.Range("F1").Resize(iR, 4)
.EntireColumn.Clear
.Value = arrRes
End With
End Sub
Sub GetChild(oDic, sPar, sChi)
Set nws = Worksheets("newsheet")
Dim vKey, aRow, j As Long
aRow = oDic(sPar)(sChi)
iR = iR + 1
' populate output array
For j = 1 To 4
arrRes(iR, j) = aRow(j)
Next
' Debug.Print Join(aRow, "|")
If oDic.exists(sChi) Then
For Each vKey In oDic(sChi).keys
'get next level
Call GetChild(oDic, sChi, vKey)
Next
End If
End Sub
Attachments
Last edited by a moderator: