Populating a combo box isn't hard, but getting the combo box to communicate with a constantly changing list is a little more difficult. Learn how to populate your combo box with a dynamic list.
Populating a userform combo box with a static list takes a little knowledge and some VBA code. Getting the combo box to update when the list updates requires a bit more work. You could update the list range every time you update it or you could create a dynamic list. By dynamic list, I really mean a dynamic range that contains a list of data items.Let's take a look at a quick example. The following userform contains one combo box, with an identifying label. You want to populate the combo box using the list in A1:A6 (on a sheet named LookupLists, which isn't shown in the figure). The first step is to create a dynamic range for the list as follows:
- Click the Formulas tab and then click Define Name in the Defined Names group to open the New Name dialog box. In Excel 2003, choose Name from the Insert menu and then select Define.
- Enter a name for the range, ColorList.
- In the Refers To control, enter the following expression: =OFFSET(LookupLists!$A$2, 0, 0, COUNTA(LookupLists!$A:$A)-1,1). LookupLists is the name of the sheet that contains the list of colors.
- Click OK.
- Open the Visual Basic Editor (VBE) by pressing [Alt]+[F11].
- From the Insert menu, choose UserForm.
- Using the Toolbox, insert a combo box control. The Toolbox should be visible when you select the userform. If necessary, choose Toolbox from the View menu.
- I added a label control and entered the text Color. You can skip this step if you like.
- Name the combo box control cboColor.
- Double-click the userform to open its module.
- Enter the sub procedure shown below:
Private Sub UserForm_Initialize()To see how the combo box works, return to the userform (close the module) and run it by clicking [F5]. The For Each statement populates the list using the data items in the range ColorList. Close the userform. Now, let's add an item to ColorList and see how well the combo box performs. Return to the sheet that contains the list and enter White in cell A7. Then, return to the VBE and run the userform a second time. As you can see, the range name ColorList automatically adapts to include the new list item, White. Subsequently, the code populates the combo box with the entire list, including White, without any modifications.
'Populate Color combo box.
Dim rngColor As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")
For Each rngColor In ws.Range("ColorList")
Next rngColorEnd Sub
In order to keep the example simple, I've bypassed any data entry task. In a real-world application, you'd probably want to copy the value selected by the combo box to a data range. That requires additional code. I've only shown you how to populate the combo box with the contents of a dynamic range (list).