Determine number of items in a listbox

sefMI

Board Regular
Joined
Apr 24, 2006
Messages
127
What is the most efficient way to determine how many items are in a listbox? I have a userform with several listboxs and the contents of each is dynamic by the selection of another listbox. I have loops that rely on knowing the max number of items in each listbox. I tried for i = 1 to ubound(listbox2)....next i, but guess that doesn't work.
 

Excel Facts

Control Word Wrap
Press Alt+Enter to move to a new row in a cell. Lets you control where the words wrap.
The answer depends on how your listboxes are being populated.

Because you said they are dynamic, you can probably get what you want with the listcount property, example:

MsgBox ListBox1.ListCount


If your listboxes are being populated with their RowSource property, ListCount will give you a potentially false number, as it will represent the count of cells in the range, which can be higher than the actual items in the listbox if some cells in the rowsource range are empty. In this case you can loop through the items with a counter, but since you asked for the most efficient method, the loop option can be examined only after you say that you are using rowsource, which I am guessing you are not doing, given your eference to the dynamic nature of the userform.
 
Upvote 0
listbox.Listcount worked for me. I'm using a collection building function to create the listboxes, if that explains anything; took it off the Internet.

Thanks
 
Upvote 0

Forum statistics

Threads
1,215,425
Messages
6,124,822
Members
449,190
Latest member
rscraig11

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