Home » excel » vba – Setting variable to the next instance in the list does not work

vba – Setting variable to the next instance in the list does not work

Posted by: admin April 23, 2020 Leave a comment

Questions:

Context: I’m coding the Dijkstra’s Shortest Path Algorithm just to practice basic patterns I’ve read on tutorials about .

I ran into a problematic situation. After long time debugging I found the issue.

Here is a minified version which shows the problem (commented):

Option Explicit

Private Sub btnSolution_Click()
    Dim N As Integer: N = 3

    'Creating one list with the first cell as head
    Dim list As New model_linked_list
    Set list.next_cell = Nothing

    'Creates list 1..N
    Dim i As Integer: i = N
    Do While i > 0
        'Creates the next cell adding to the start (after the head-cell)
        Dim cell As New model_linked_list
        cell.city = i
        Set cell.next_cell = list.next_cell

        'Update head-cell
        Set list.next_cell = cell
        i = i - 1
    Loop

    'All good till here, but when I try to loop over the list:

    Dim item As model_linked_list
    Set item = list.next_cell

    'You will to set a breakpoint in this line to avoid infinite loop
    Do While Not item Is Nothing

        MsgBox item.city 'Always shows "1"

        'This is the problematic line
        Set item = item.next_cell 'It seems like it does nothing, literally
    Loop

End Sub

enter image description here

My model_linked_list is just:

Option Explicit

Public city As Integer
Public next_cell As model_linked_list

Illustrating, the above code should just create one list like this:

enter image description here

It seems like Set is just not working when I try to go to the next cell in the list. Have anyone seen this before? How to work around it?

Thanks in advance.

How to&Answers:

Your mistake is here:

Dim cell As New model_linked_list

change it into:

Dim cell As model_linked_list
Set cell = New model_linked_list

In short, with Dim cell As New model_linked_list, the “New” operator was executed only once, so you were manipulating the same object in all your iterations.