2013-07-19 124 views
-1

我想從兩個不同的下拉列表中選擇在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

+0

可能的重複http://stackoverflow.com/questions/17718840/dropdown-of-the-data-validation-to-select-multiple-items-for-several-columns – pnuts

+0

嗨@pnuts。另一個問題也沒有回答。但它是相似的,因爲我需要能夠在下拉列表中選擇值並將它們放在同一個單元格中。所顯示的代碼只能用於一列。 –

回答

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