首页 > 解决方案 > 如何在一张表中获得两个 Wocksheet_Changes 以在下拉列表中进行多项选择

问题描述

我想从一个 Excel 工作表上的多个列的下拉列表中进行多项选择。我从每张纸一列的下拉列表中找到了多项选择的代码,但我需要五个。它自己的代码适用于一列。

我已经尝试将 Worksheet_Changes 命名为

那没有用。结果是我无法从下拉列表中为一个单元格选择多个名称

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rngDV As Range
    Dim wert_old As String
    Dim wertnew As String

    On Error GoTo Errorhandling

    If Not Application.Intersect(Target, Range("B4:B999")) Is Nothing Then
        Set rngDV = Target.SpecialCells(xlCellTypeAllValidation)
        If rngDV Is Nothing Then GoTo Errorhandling

        If Not Application.Intersect(Target, rngDV) Is Nothing Then
            Application.EnableEvents = False
            wertnew = Target.Value
            Application.Undo
            wertold = Target.Value
            Target.Value = wertnew

            If wertold <> "" Then
                If wertnew <> "" Then
                    Target.Value = wertold & ", " & wertnew
                End If
            End If
        End If

        Application.EnableEvents = True
    End If

最后,我想从下拉选择中选择多个名称,在五个不同的列中

If Not Application.Intersect(Target, Range("B4:B999")) Is Nothing Then

If Not Application.Intersect(Target, Range("C4:C999")) Is Nothing Then

If Not Application.Intersect(Target, Range("D4:B999")) Is Nothing Then
...
...
...

标签: excelvba

解决方案


使用Application.Union 方法来组合您要在其中运行代码的范围。然后将Intersect它们与Target如下所示:

If Not Application.Intersect(Target, Union(Me.Range("B4:B999"), Me.Range("C4:C999"), Me.Range("D4:B999"))) Is Nothing Then

在此处输入图像描述


推荐阅读