如何在VBA脚本中选择多个单元格

时间:2017-10-17 15:56:33

标签: excel vba excel-vba

语句If Target.Address = "$I$2" Then仅选择I2单元格。

如何选择整个列而不只是一个单元格? 这是我的代码

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

1 个答案:

答案 0 :(得分:1)

您可能想查看整个专栏"我"而不是细胞" I2"。 此条件应从

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

    If Target.Column = 9 Then

因此宏会将其视为完整列。