Excel

Fill combobox with ordered list

Ease of Use

Easy

Version tested with

2003 

Submitted by:

mdmackillop

Description:

Enters a sorted list of unique items in a combobox from a named range and adds new items to the range. 

Discussion:

Use data from an unsorted list to aid in data entry. Thanks to DRJ for the Bubblesort 

Code:

instructions for use

			

'Place all code in the Userform Option Explicit Dim FArray() Dim DataList As Range Dim MyList As String Private Sub UserForm_Initialize() Dim Found As Long, i As Long Dim cel As Range 'Set Range Name to suit MyList = "Data" Set DataList = Range(MyList) ReDim FArray(DataList.Cells.Count) i = -1 For Each cel In DataList On Error Resume Next Found = Application.WorksheetFunction.Match(CStr(cel), FArray, 0) If Found > 0 Then GoTo Exists i = i + 1 FArray(i) = cel Exists: Found = 0 Next ReDim Preserve FArray(i) Call BubbleSort(FArray) ComboBox1.ListRows = i + 1 ComboBox1.List() = FArray End Sub Private Sub ComboBox1_AfterUpdate() Dim MyAdd As String Dim Found As Long On Error Resume Next Found = Application.WorksheetFunction.Match(ComboBox1, FArray, 0) If Found > 0 Then DoEvents Else DataList.End(xlDown).Offset(1) = ComboBox1 Set DataList = Union(DataList, DataList.End(xlDown)) MyAdd = "=" & ActiveSheet.Name & "!" & DataList.Address ActiveWorkbook.Names.Add Name:=MyList, _ RefersTo:=MyAdd End If End Sub Private Sub CommandButton1_Click() Cells(Cells.Rows.Count, 4).End(xlUp).Offset(1) = ComboBox1 Set DataList = Nothing Unload UserForm1 End Sub Sub BubbleSort(MyArray As Variant) Dim First As Integer Dim Last As Integer Dim i As Integer Dim j As Integer Dim Temp As String Dim List As String First = LBound(MyArray) Last = UBound(MyArray) For i = First To Last - 1 For j = i + 1 To Last If MyArray(i) > MyArray(j) Then Temp = MyArray(j) MyArray(j) = MyArray(i) MyArray(i) = Temp End If Next j Next i End Sub

How to use:

  1. In the VB Editor, add a Userform module
  2. Paste the code into the userform code area
  3. Add a ComboBox and CommandButton to the form
  4. Select a column of data and give it the RangeName "Data".
 

Test the code:

  1. Open the userform and select or add a new item.
  2. The item will be written to column D and new items added to the list for future use.
 

Sample File:

DisplayUniqueList.zip 16.3KB 

Approved by mdmackillop


This entry has been viewed 553 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express