【问题标题】:Apply VBA code to multiple columns - to allow selection of multiple options from data validation list将 VBA 代码应用于多列 - 允许从数据验证列表中选择多个选项
【发布时间】:2021-05-16 00:59:37
【问题描述】:

我设置了一个包含多个列的电子表格,其中一些列具有数据验证下拉列表。我需要用户能够从下拉列表中选择多个选项。我已经使用下面的 VBA 为一列实现了这一点,但是我正在努力寻找将其应用于多列的正确方法。请有人帮忙。 目前我使用了'Target.Column = 9',但是我需要将它应用到第 3、4、5、6、9 列。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Column = 9 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

提前致谢

【问题讨论】:

    标签: vba dropdown multiple-columns multiple-select


    【解决方案1】:

    你可以扩展你的If

    If Target.Column = 9 or Target.Column = 3

    但有时Select Case 有点整洁。

    Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim Oldvalue As String
    Dim Newvalue As String
    
    Application.EnableEvents = True
    
    On Error GoTo Exitsub
    
    Select Case Target.Column
        Case 3, 4, 5, 6, 9
          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 Select
    
    Exitsub:
    Application.EnableEvents = True
    
    End Sub
    

    【讨论】:

    • 完美!正是我所需要的——非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2020-07-04
    相关资源
    最近更新 更多