2017-08-30 63 views
3

我會說我不擅長VBA。我有一個VBA代碼,在一個單元格中從選定列表中追加多個值。代碼有效,但現在我想將代碼應用於多個單元格。將VBA宏應用於多個單元格

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 

如何延長我的代碼使用單元格區域

$A$7:$A$18 

,而不是"$A$7",這樣我可以申請VBA代碼到多個單元格在Excel中。

回答

5

變化

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

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

優雅的,有給予好評。 –

0

我使用通配符。

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

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