Ease of Use
Easy
Version tested with
2003
Submitted by:
Ken Puls
Description:
This is very simple example of how to verify that an item in a userform listbox has been selected, and identify which item was chosen. This code is specifically designed for a single selection listbox. If you need code to allow multiple selections, please see KB Entry //www.vbaexpress.com/kb/getarticle.php?kb_id=369
Discussion:
When using a listbox on a userform, it is often important to ensure that your user has picked an item, and then identify what the chosen item was. This is a very simple illustration of how to do both. The listbox in this example is filled via code, but it can easily be filled from a worksheet range as well, using a loop.
Code:
instructions for use
How to use:
- Open the VBE [press Alt+F11].
- If the project explorer is not open, press CTRL + R to open it.
- Navigate to the desired file, right click it and choose "Insert UserForm".
- Double click the userform in the project explorer.
- If the "Toolbox" toolbar is not open, open it from the View menu.
- Add a listbox and two commandbuttons to the userform.
- Right click one of the commandbuttons and choose "Properties".
- In the window that pops up, change the [Name] property to cmdOkay, and the Caption variable to Okay.
- Using the same method, change the second button's [name] to cmdCancel, and its Caption to Cancel.
- Copy the userform subroutines from above [everything up to the line that denotes the Standard module code].
- Right click the UserForm in the project explorer and choose "View Code".
- Paste the code in the right pane.
- Copy the last procedure from above [Sub Launch].
- In the project explorer, right click the project name again and choose Insert -> Module.
- Paste the code in the right pane.
- Press Alt + Q to close the VBE.
- Save workbook before any other changes.
Test the code:
- From the main Excel interface, press Alt + F8 to open the macro dialog box.
- Choose Launch and click Run.
- Try clicking okay without anything selected, and then try after selecting an item.
Sample File:
ListBoxSingleSelect.zip 10.05KB
Approved by mdmackillop