Excel中多行的Target.address

时间:2017-01-26 00:12:56

标签: excel-vba vba excel

我需要引用整个Excel电子表格列,并使用VBA下拉列表。我上传的代码仅适用于"$M$2"的单个单元格。如何为整列定义范围?

Private Sub Worksheet_Change(ByVal Target As Range)

' To Select Multiple Items from a Drop Down List in Excel

Dim Oldvalue As String
Dim Newvalue As String

On Error GoTo Exitsub
If Target.Address = "$M$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
            Target.Value = Oldvalue & ", " & Newvalue
        End If
    End If
End If
Application.EnableEvents = True

Exitsub:
Application.EnableEvents = True

End Sub

1 个答案:

答案 0 :(得分:2)

首先,Target可以是单个单元格或多个单元格,具体取决于用户更改的内容

要测试M列(且仅在列M)中是否有任何单元格发生变化,请使用

If Target.EntireColumn.Address = "$M:$M" Then

要测试Target中的任何单元格是否在M列中

Dim rng As Range
Set rng = Application.Intersect(Target, Me.Columns("M"))
If Not rng Is Nothing Then

注意:您需要修改其余代码以允许Target多个单元格