将 VBA 代码应用于多列 - 允许从数据验证列表中选择多个选项

问题描述

我设置了一个包含多列的电子表格,其中一些列有数据验证下拉列表。我需要用户能够从下拉列表中选择多个选项。我已经使用下面的 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

提前致谢

解决方法

您可以扩展您的 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