I am trying to create a multi select dropdown list with Excel VBA. I have the following code for Sheet1.
With Range("B27").Validation
.Delete
End With
With Range("B27")
.Value = "[Select from drop down]"
End With
With Range("B27").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop,Formula1:="=DropDownList_data!D1:D3")
.IgnoreBlank = True
End With
Cells D1, D2 and D3 in the DropDownList_data tab contain the text Item1,Item2,Item3 respectively. I have made this a multi select list by writing code in the Worksheet_Change event. When I select the 3 items consecutively, Item1,Item2,Item3 appears in Cell B27. However, when I manually delete ,Item3 from the cell the following error appears. "This value doesn't match the data validation restrictions defined for this cell."
The following is the code in the Worksheet_Change event.
Dim Newvalue, Oldvalue As String
On Error GoTo Exitsub
Application.EnableEvents = False
If Target.Address="$B$27" Then
If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
Else: If Target.Value = "" Then GoTo Exitsub Else
Newvalue = Target.Value
Application.Undo
Oldvalue = Target.Value
If Oldvalue = "" Or Oldvalue = "[Select from drop down]" Then
Target.Value = Newvalue
Else
Dim strArray() As String
strArray = Split(Oldvalue, ",")
If IsInArray(Newvalue, strArray) Then
Target.Value = Oldvalue
Else
Target.Value = Oldvalue & "," & Newvalue
End If
End If
End If
End If
Exitsub:
Application.EnableEvents = True
How can I manually delete an item after I have selected it?
Worksheet_Changeevent code, you maybe will receive an answer. Otherwise, nobody is able to understand what "when I manually delete ,Item3 from the cell the following error appears" means. I can only suppose. The cell validation means exactly that it admits only selecting elements from the list.