I have written this sub that recursively parses a tree of HTML pages. My problem is that when I get to the bottom of the tree and the sub exits to the previous level, all objects are empty. Here is the full code:
Public Row As Integer
Public objIE As Object
Sub GetBranches()
Set objIE = CreateObject("InternetExplorer.Application") ' create new browser
objIE.Visible = True ' make IE visible for viewing login
Row = 2 ' start at line 2 (first line is headers)
GetBranchesRecursively ("241653")
End Sub
Sub GetBranchesRecursively(BranchID As String)
Dim CurrentBranch As Object
Dim subBranches, subBranch As Object
Dim SubBranchID As String
' navigate IE to Branch ID
objIE.navigate "https://casadasereia.net/vbatests/viewtree" & BranchID & ".html"
' wait for browser
Do While objIE.Busy = True Or objIE.readyState <> 4
DoEvents
Loop
Set CurrentBranch = objIE.document.getElementById(BranchID)
' store name and ID of current Branch
Worksheets("Data").Range("A" + CStr(Row)) = Trim(CurrentBranch.innerText) ' Branch name is in the HTML A tag
Worksheets("Data").Range("B" + CStr(Row)) = BranchID
Row = Row + 1
' list of subBranches is the list of LI elements of the UL element adjacent to the A tag
Set subBranches = CurrentBranch.NextSibling.NextSibling.getElementsByTagName("li")
For Each subBranch In subBranches
SubBranchID = subBranch.getElementsByTagName("A")(0).ID ' BranchID is in the id property of the HTML A tag
If InStr(subBranch.className, "node") <> 0 Then
' This is a node, store data and move to next in the list
Worksheets("Data").Range("A" + CStr(Row)) = Trim(subBranch.innerText) ' name is in the HTML A tag
Worksheets("Data").Range("B" + CStr(Row)) = SubBranchID
Row = Row + 1
Else
' This is a branch, move down to the branch
GetBranchesRecursively (SubBranchID)
End If
Next
End Sub
At the last level of recursion (BranchID 99816) there are 4 nodes and no branches. Their data is correctly stored and, at the end of the For loop, control is passed back to the previous level but when that happens all objects are empty. This is what the debugger shows me:
Anyone knows why these variables show as empty when they were properly filled before the recursive call?