abhishek
abhishek

Reputation: 1

Persistent values in ListBox in Excel VBA

This is my first question in this forum and I am very new to Excel VBA.

I have a text box that has an Exit event. My requirement is that when I fill that textbox and exit from there its values should be populated in ListBox. Now, when I am trying to insert the value again inside textbox, it overwrites previous value inside the ListBox. I want the values to be persistent. So the values entered in text box should come in sequence.

Here is what I tried :

ListBox1.ColumnCount = 2 

ListBox1.AddItem 
ListBox1.List(0) = TextBox2.Text 

But then how can I take the next value from Text box and make it visible in List box...(so if I enter 3 values in text box it should show three rows in Listbox)

Upvotes: 0

Views: 383

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149295

When you say ListBox1.List(0) = TextBox2.Text, you are telling the code to always add (replace on 2nd instance) to the first item in the listbox.

Is this what you are trying?

Private Sub UserForm_Initialize()
    ListBox1.ColumnCount = 2
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    ListBox1.AddItem
    ListBox1.List(ListBox1.ListCount - 1, 0) = TextBox1.Text
End Sub

If you do not need a multi column listbox then the below will also do.

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    ListBox1.AddItem TextBox1.Text
End Sub

Upvotes: 4

Related Questions