Home » excel » excel – Populating a column from few textboxes (VBA)

excel – Populating a column from few textboxes (VBA)

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need help with a VBA script.
Our teacher has told us to use:

ListBox1.AddItem ComboBox1.Text And Val(TextBox4.text) And ListBox1.AddItem
FormatCurrency(price, 2)

It is supposed to show both the name from ComboBox1, the quantity from TextBox4 and price from TextBox5 (formatted into ‘price’ variable) but it gives me an error.

I decided to try to use:

ListBox1.AddItem ComboBox1.Text  
ListBox1.AddItem Val(TextBox4.Text)  
ListBox1.AddItem FormatCurrency(price, 2)

But the result is this:

enter image description here

Where as it is supposed to be one next to the other (mew 1 £3.50), instead of one above the other.

How to&Answers:

You need to specify the column count and the column width of the listbox in case you want it to behave like a multicolumn listbox.

Try this

Option Explicit

Private Sub UserForm_Initialize()
    ListBox1.ColumnCount = 3
    ListBox1.ColumnWidths = "50;50"
End Sub

Private Sub CommandButton1_Click()
    With ListBox1
        .AddItem
        .List(.ListCount - 1, 0) = ComboBox1.Text  
        .List(.ListCount - 1, 1) = Val(TextBox4.Text) 
        .List(.ListCount - 1, 2) = FormatCurrency(price, 2)
    End With
End Sub

enter image description here

EDIT: Followup from comments.

The reason why you shouldn’t use & is because the data in columns will not be aligned if you have multiple rows. See this example

Private Sub CommandButton1_Click()
    With ListBox1
        .AddItem "Sid" & " " & "Rout" & " " & "Sample"
        .AddItem "Hello" & " " & "World" & " " & "Sample"
        .AddItem "Another" & " " & "Example" & " " & "Sample"
        .AddItem "Yet" & " " & "another" & " " & "Sample"
    End With
End Sub

And this is what you will get

enter image description here