mk mcmahon
mk mcmahon

Reputation: 23

How to select multiple cells in VBA script

The statement If Target.Address = "$I$2" Then selects just the I2 cell.

How can I select the entire column instead of just one cell? Here is my code

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
'Code by Sumit Bansal from https://trumpexcel.com
' To Select Multiple Items from a Drop Down List in Excel
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Address = "$I$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: 1

Views: 361

Answers (1)

shrivallabha.redij
shrivallabha.redij

Reputation: 5902

You probably want to check the entire column "I" instead of cell "I2". This condition shall be changed from

    If Target.Address = "$I$2" Then

to

    If Target.Column = 9 Then

So that macro will consider it for complete column.

Upvotes: 1

Related Questions