Populate ListBox with RecordSet

timorrill

Well-known Member
Joined
Sep 20, 2006
Messages
528
I am currently using the following code to populate a list box with the contents of an ADODB recordset:

Code:
Private Sub PopulateListBox()
    With Me.lboxRecords
        .ColumnCount = rsListBox.Fields.Count
        .Column = rsListBox.GetRows
        .ColumnHeads = True
    End With
End Sub

Is there a way to easily specify the column titles (I want the columns to have the same names that the fields in the recordset have)? Also, I'd like to automatically resize the ListBox so that it shows all the fields at once (i.e., no horizontal scroll bars). How about code for this?
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
The only way to populate the headers of a listbox is to put the data into a worksheet and use the listbox's Rowsource property to populate the data (the headers come from the row above the Rowsource). Your alternative is to add label controls above the listbox and size and change the captions as required.
To autofit the columns you would need to know the longest item in each column and then, unless you are using a fixed-width font, you would need API calls to work out the length required, which would, IMO, be horribly complicated.
 
Upvote 0

Forum statistics

Threads
1,215,543
Messages
6,125,429
Members
449,223
Latest member
Narrian

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top