kamsteg
kamsteg

Reputation: 31

If Target Address - how can I use a range?

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

Upvotes: 2

Views: 5974

Answers (2)

Vityata
Vityata

Reputation: 43585

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

Upvotes: 1

Pᴇʜ
Pᴇʜ

Reputation: 57683

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

Upvotes: 3

Related Questions