简体   繁体   中英

Apply VBA macro to multiple cells

I would say I am not expert in VBA. I have a VBA code that append multiple values from selected list in one cell. The code works but now I would like to apply the code to multiple cells.

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 = "$A$7" 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 & "," & Chr(10) & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub

How can I extend my code to use cell range

$A$7:$A$18 

instead of "$A$7" so that I can apply the VBA code to multiple cells in Excel.

Change

If Target.Address = "$A$7" Then

to

If Not Intersect(Target, Range("A7:A18")) Is Nothing Then

I used wild cards.

If Target.Address = "$A$7" Then

To

If Target.Address Like "$A$[7-9]" Or Target.Address Like "$A$1[0-8]" Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM