The Fruits contains list - Apple,Banana,Orange and Colors contains list - Red,Black,Orange
so when I multi select the Fruits as well as Colors from drop-down list from cell "G1". Then the "Offset(0, -1)" means "F1" shows me the combine output list as - (Apple, Banana, Orange, Red, Black, Orange). So, The list in cell "F1" contains duplicate value Orange and it prints 2 times. It should pick up only unique items from the selected one and remove the duplicate one and should print in cell F1 as - (Apple, Banana, Orange, Red, Black).
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range, oldVal As String, newVal As String
Dim arr As Variant, El As Variant
If Target.count > 1 Then GoTo exitHandler
If Target.value = "" Then
Application.EnableEvents = False
Target.Offset(0, -1).value = ""
Application.EnableEvents = True
Exit Sub
End If
On Error Resume Next
Set rngDV = cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Not Intersect(Target, rngDV) Is Nothing Then
Application.EnableEvents = False
newVal = Target.value: Application.Undo
oldVal = Target.value: Target.value = newVal
If Target.Column = 7 Then
If oldVal <> "" Then
If newVal <> "" Then
arr = Split(oldVal, ",")
For Each El In arr
If El = newVal Then
Target.value = oldVal
GoTo exitHandler
End If
Next
Target.value = oldVal & "," & newVal
Target.EntireColumn.AutoFit
End If
End If
End If
writeSeparatedStringLast Target
End If
exitHandler:
Application.EnableEvents = True
End Sub
Sub writeSeparatedStringLast(rng As Range)
Dim arr As Variant, arrFin As Variant, El As Variant, k As Long, listBox As MSForms.listBox
Dim arrFr As Variant, arrVeg As Variant, arrAnim As Variant, El1 As Variant
Dim strFin As String ', rng2 as range
arrFr = Split("Apple,Banana,Orange", ",")
arrVeg = Split("Onion,Tomato,Cucumber", ",")
arrAnim = Split("Red,Black,Orange", ",")
arr = Split(rng.value, ",")
For Each El In arr
Select Case El
Case "Fruits"
arrFin = arrFr
Case "Vegetables"
arrFin = arrVeg
Case "Colors"
arrFin = arrAnim
End Select
For Each El1 In arrFin
strFin = strFin & El1 & ", "
Next
Next
strFin = left(strFin, Len(strFin) - 1)
With rng.Offset(0, -1)
.value = strFin
.WrapText = True
.Select
End With
End Sub
'Firstly run the next Sub, in order to create a list validation in range "G1":
Sub CreateValidationBis()
Dim sh As Worksheet, rng As Range
Set sh = ActiveSheet
Set rng = sh.Range("G1")
With rng.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="Fruits,Vegetables,Colors"
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
End Sub