Search code examples
excelvbauserform

How do I get the text from 0+n columns in a UserForm List Box?


So this is for a purchase order data entry application where the user enters each item from a PO into the UserForm listbox with different attributes of the item in each column. For example:

Column 1: Name of the product Column 2: Qty purchased Column 3: Price

Everything works great, but I cannot get the values out of the 0+n columns in the list box. I've only found this code, but it only gets me the text value for the nth column:

ListBox1.ListIndex = n
MsgBox ListBox1.Text

I can get the value for (n, column 0), which I need. But I also need the value of (n, column 1), (n, column 2), etc.

Help!!!


Solution

  • You can specify column number and row number to return value from ListBox control. Below is simple code to return value from 3rd column, 3rd row.

    Note: ListBox indexing always start from zero (0).

    Private Sub CommandButton1_Click()
    Dim iCol As Long
    Dim iRow As Long
    
        iCol = 2 'Specify column number
        iRow = 2 'Specify row number
    
        MsgBox ListBox1.List(iRow, iCol)
    
    End Sub
    

    If you want to loop through all elements then you have to use a For loop. See this post for details.