Friday, November 9, 2007

How to create a multicolumn list box

This is the first in a series of code explanations I will post on this website.

I have recently had to create a multi-column list box so that I can display a list of customers along with some of their other attributes. To tackle this problem I created arrays that I used to then populate the list box:

'First, I declare the array.
'This one will give me 2 rows and 3 columns:

Dim vntArray(0 To 1, 0 To 2) As Variant

'Next, I populate the array with the customers' info
vntArray(0, 0) = "Smith" 'last name
vntArray(0, 1) = "Bill" 'first name
vntArray(0, 2) = "05/23/1978 'Birth date

vntArray(1, 0) = "Bonds"
vntArray(1, 1) = "Barry"
vntArray(1, 2) = "07/24/1964"

'Now to populate the list box with this array:
With Me.listBox
.ColumnCount = 3
.List = vntArray
End With

This adds the array to the list box and will treat each row as a unit so you essentially have a customer in each row.

Note: you could use a loop to read through an excel worksheet and populate this array automatically (hint: you need to read how big you will require the array to be before populating it), I will explain this in a future post or sooner if I get any requests.

No comments: