2

Hi I am currently making a multiple list validation, but currently I am only able to make it to one cell E2 and I wish to make it in a range to go from E2:E40. I was thinking something along $E$2:$E$40. However, this does not work.

Private Sub Worksheet_Change(ByVal Target As Range)
' To allow multiple selections in a Drop Down List in Excel (without repetition)
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Address = "$E$2" Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
      If Oldvalue = "" Then
        Target.Value = Newvalue
      Else
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & ", " & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
kamsteg
  • 31
  • 4
  • 4
    Although this works in VBA `Else:`, consider avoiding it, looks ugly and may cause problems - https://stackoverflow.com/questions/41983020/vba-how-the-colon-works-in-vba-code-with-condition – Vityata Jun 09 '21 at 08:28

2 Answers2

2

Use something like this

Dim AffectedCells As Range
Set AffectedCells = Intersect(Me.Range("E2:E40"), Target)

If Not AffectedCells Is Nothing Then
    ' do your stuff here …
End If

AffectedCells contains all cells within E2:E40 that were actually changed.

Make sure you loop through AffectedCells to handle each cell

Dim Cell As Range
For Each Cell In AffectedCells.Cells
    ' do your stuff with each Cell here …
Next Cell
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
1

Use this pattern for the intersections and consider building on it:

Private Sub Worksheet_Change(ByVal Target As Range)
        
    Dim intersectRange As Range
    Set intersectRange = Target.Parent.Range("E2:E40")
    
    If Not Intersect(Target, intersectRange) Is Nothing Then
        Debug.Print "Intersected " & Target.Address
    Else
        Debug.Print "Not intersected " & Target.Address
    End If
        
End Sub
Vityata
  • 42,633
  • 8
  • 55
  • 100