在多个下拉列表中选择多个值

时间:2013-07-19 10:31:08

标签: excel vba excel-vba

我试图从两个不同的下拉列表中选择excel中的多个值。我有一些代码可以在一个下拉列表中选择多个值,并希望能够对另一个具有不同值的下拉列表执行相同的操作。我可以使用下面的代码并对其进行修改,还是有另一种更简单的方法可以做到这一点?

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String

If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler

If rngDV Is Nothing Then GoTo exitHandler

If Intersect(Target, rngDV) Is Nothing Then
   'do nothing
Else
  Application.EnableEvents = False
  newVal = Target.Value
  Application.Undo
  oldVal = Target.Value
  Target.Value = newVal
  If Target.Column = 7 Or Target.Column = 45 Then
    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
      Target.Value = oldVal _
        & ", " & newVal
      End If
    End If
  End If
End If    

exitHandler: Application.EnableEvents = True End Sub

1 个答案:

答案 0 :(得分:0)

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String

If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler

If rngDV Is Nothing Then GoTo exitHandler

If Intersect(Target, rngDV) Is Nothing Then
   'do nothing
Else
  Application.EnableEvents = False
  newVal = Target.Value
  Application.Undo
  oldVal = Target.Value
  Target.Value = newVal
  If Target.Column = 7 Or Target.Column = 45 Then
    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
      Target.Value = oldVal _
        & ", " & newVal
      End If
    End If
  End If
End If    
exitHandler: Application.EnableEvents = True End Sub

我使用了条件Or,可以从两个不同的下拉列表中选择多个值。这显示在代码If Target.Column = 7 Or Target.Column = 45 Then