2011-05-31 50 views
0

我正在使用以下代碼從數據驗證單元格中選擇多個項目。它可以工作,但我需要對單元格內的條目進行排序,以便無論用戶從下拉列表中選擇的順序如何,都不會得到梨,蘋果,桔子,結果將是蘋果,桔子,梨。在單個單元格中以alpabetically排序分隔字符串

這也將是很好(但不是必要的重複檢查。感謝您的幫助!急需!

Option Explicit 
' Developed by Contextures Inc. 
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 = 3 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

您可以將oldVal拆分成一個數組,找到將newVal插入到適當位置的位置,然後將數組重新加入到字符串中。 – Neil 2011-05-31 20:31:06

回答

0

沒有進入不同的排序算法,你可以暫時的值存儲在範圍上然後使用該範圍,然後在代碼中使用[range].sort()函數對範圍進行排序,一旦排序,就可以將它們讀回到Target.Value單元格中,並對其進行劃分。排序,但在它被讀回target.value之前,迭代thro ü範圍內的每個單元格,如果單元格等於下面的單元格,則刪除並向上移動值。

相關問題