如何将Visual Basic多项选择应用于列?

时间:2019-06-20 14:11:30

标签: excel vba

我不熟悉Excel代码的编程,但是我能够找到一个代码来重复应用下拉列表中的多选。但是,它仅适用于该单元格,因此我要遍历每个单元格以将该规则应用于每个单独的单元格。如果可能的话,我想将此规则编码应用于列!

Private Sub Worksheet_Change(ByVal Target As Range)
    'Code by Sumit Bansal from https://trumpexcel.com
    ' To allow multiple selections in a Drop Down List in Excel (without repetition)
    Dim Oldvalue As String
    Dim Newvalue As String
    Application.EnableEvents = True
    On Error GoTo Exitsub

    If Target.Address = "$E$13" 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 :(得分:2)

您要检查Target.Address,而不是检查Target.Column

If Target.Column = 5 Then

您可能还想检查Target只是一个列。例如,Range("E5:G5").Column仍将返回5

您可以执行以下操作:

If Target.Columns.Count = 1 Then

或一起:

If Target.Columns.Count = 1 And Target.Column = 5 Then