Zorobay

Multi Select Lists in Excel (VBA)

Sep 7th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function IsIn(x, arr) As Boolean
  2.     Dim found As Boolean
  3.     found = False
  4.    
  5.     For Each elem In arr
  6.         If elem = x Then
  7.             found = True
  8.             Exit For
  9.         End If
  10.     Next
  11.     IsIn = found
  12. End Function
  13.  
  14.  
  15. Private Sub Worksheet_Change(ByVal Target As Range)
  16. ' Developed by Contextures Inc.
  17. ' www.contextures.com
  18. ' Edited and extended by Sebastian Hegardt
  19.  
  20. ' --- Declare Variables ---
  21. Dim rngDV As Range
  22. Dim oldVal As String
  23. Dim newVal As String
  24. Dim column As Integer
  25. Static columns As Variant
  26.  
  27. ' --- Declare constants ---
  28. 'Separator string to use. Use vbNewLine for separation by new line
  29. Const separator As String = ", "
  30. 'Array of columns to apply this script to
  31. columns = Array(3, 5)
  32.  
  33. If Target.Count > 1 Then GoTo exitHandler
  34.  
  35. On Error Resume Next
  36. Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
  37. On Error GoTo exitHandler
  38.  
  39. If rngDV Is Nothing Then GoTo exitHandler
  40.  
  41. If Intersect(Target, rngDV) Is Nothing Then
  42.    'do nothing
  43. Else
  44.     Application.EnableEvents = False
  45.     newVal = Target.Value 'Save current new value
  46.    Application.Undo
  47.     oldVal = Target.Value 'Undo and save old value
  48.    Target.Value = newVal
  49.    
  50.     If IsIn(Target.column, columns) Then
  51.         If oldVal = "" Then
  52.             'do nothing
  53.        ElseIf newVal = "" Then 'Nothing was selected
  54.            'do nothing
  55.        Else
  56.             Target.Value = oldVal & separator & newVal
  57.         End If
  58.     End If
  59. End If
  60.  
  61. exitHandler:
  62.   Application.EnableEvents = True
  63. End Sub
Advertisement
Add Comment
Please, Sign In to add comment