Search code examples
excelvbaarraylistuserform

VBA : Fill a Listbox with an ArrayList


Does someone knows how can I add an ArrayList to a ListBox that is in a userform. I've tried this code in the UserForm1 module but it doesn't display anything when the UserForm1 window is open.

Public Sub here()
Dim MyList As Object
Set MyList = CreateObject("System.Collections.ArrayList")

MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"

UserForm1.ListBox1.List = MyList
End Sub

I've read some articles and I understood that I needed to activate mscordlib.dll Library but idk what else I can do to make it work.

EDIT

Here's the userform with the actual program :

Nothing happens


Solution

  • This works fine for me with the adjusted MyList.Array..

    enter image description here

    Like FaneDuru says, you need to trigger your sub in some way; in this case, I used the click event of the Userform. Only thing needed to show the 3 items was click the form et voila. Usually, you'd want this linked to a button (click event of that) on the form or in the initialization of the userform, like so:

    Private Sub UserForm_Initialize()
        here2
    End Sub
    
    Private Sub here2()
        Dim MyList As Object
        Set MyList = CreateObject("System.Collections.ArrayList")
        
        MyList.Add "Item1"
        MyList.Add "Item2"
        MyList.Add "Item3"
        MyList.Add "Yes!"
        
        UserForm1.ListBox1.List = MyList.ToArray
    End Sub
    

    enter image description here