I actually used a Dictionary when I did it, based on code I found elsewhere. This is a cut down version of the code:
It is passed the range where the data is present and the cell where the Data Validation List is required.
' Generic Worksheet Selection Change subroutine
Sub WSC_x( _
ByVal rRawData As Variant, _
ByVal sDVOut As Variant)
' Worksheet Selection Change processing routine
' This routine creates the Primary DD DV List
Dim awf As WorksheetFunction: Set awf = WorksheetFunction
Dim InputList ' Input Array
Dim SDVString As String ' data Validation output string
sTMSDebug "WSC_x", rRawData.Address, sDVOut
' store the range in an array
InputList = _
awf.Transpose(rRawData)
' sort the array
' uses default parameters
' all entries ascending
' QSortInPlace InputList <<< from Chip Pearson's site
' create a "dictionary" of the DV data
Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
Dim i As Long
For i = LBound(InputList) To UBound(InputList)
d(InputList(i)) = 1
Next 'i
' extract unique entries from the "raw data" range
' store in a comma delimited string
Dim V As Variant
SDVString = ""
For Each V In d.Keys()
' d.Keys() is a Variant array of the unique values in myArray.
' v will iterate through each of them.
' Debug.Print v
If V <> "" Then
SDVString = SDVString & V & ","
End If
Next 'V
On Error Resume Next
SDVString = Left(SDVString, Len(SDVString) - 1)
' If there is no data, set the string to "Error"
' This ensures the Data Validation Add does not fail
If Err.Number <> 0 Then SDVString = "Error"
On Error GoTo 0
' Add the Data Validation to the Primary Drop Down List
With ActiveSheet
.Unprotect Password:=shPW
On Error Resume Next
With .Range(sDVOut).Validation
.Delete
.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, _
Formula1:=SDVString
.IgnoreBlank = False
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
On Error GoTo 0
sProtectSheet ActiveSheet
End With
' End of Generic Worksheet Selection Change subroutine
End Sub
Basically, it takes a range and puts that into an array. It then creates an array (Dictionary) of unique entries. Then it loops through the unique entries and builds a comma separated string. This is then used as the Data Validation List. Bit tedious but it's quite fast and works (at least in the project I created it for.)
Regards, TMS
Bookmarks