2011-05-31 54 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 ü范围内的每个单元格,如果单元格等于下面的单元格,则删除并向上移动值。

相关问题